Меню

Возвращаемое значение пропущено fscanf ошибка

I am brand new to coding C (and coding in general) so I have been practicing with some random programs. This one is supposed to determine the cost of a transit ticket (Translink Vancouver prices) based on the user’s age and the desired number of «zones» (how far they would like to go). I have compiled it successfully but for some reason which I can not figure out, the scanf functions are being ignored. How do I fix this? Please keep in mind I have only been coding for a few days. Thanks!

int main(void) {

int zones;
int age;
double price = 0.00;

printf("Welcome to TransLink cost calculator!nn");
printf("Please enter the desired number of zones (1, 2, or 3) you wish to travel: ");
scanf("%d", &zones);

if (zones < 1) {
    printf("Invalid entryn");
    price = 0.00;
}

else if (zones > 3) {
    printf("Invalid entryn");
    price = 0.00;
}

else if (zones == 1) {

    printf("Please enter your age: ");
    scanf("%d", &age);

    if (age < 0.00) {
        printf("Invalid Aage");
    }
    else if (age < 5) {
        price = 1.95;
    }
    else if (age >= 5) {
        price = 3.00;
    }
}

else if (zones == 2) {

    printf("Please enter your age: ");
    scanf("%d", &age);

    if (age < 0) {
        printf("Invalid Aage");
    }
    else if (age < 5) {
        price = 2.95;
    }
    else if (age >= 5) {
        price = 4.25;
    }
}

else if (zones == 3) {

    printf("Please enter your age: ");
    scanf("%d", &age);

    if (age < 0) {
        printf("Invalid Aage");
    }
    else if (age < 5) {
        price = 3.95;
    }
    else if (age >= 5) {
        price = 4.75;
    }
}

printf("The price of your ticket is: $%.2f + taxn", price);

system("PAUSE");
return 0;
}

asked Sep 19, 2019 at 5:25

Caiden Keller's user avatar

5

A bit too much here to put in a comment.

I use a version of Visual C but it never complains about the return value from scanf not being used. What it does is to complain that scanf is unsafe and deprecated, when it isn’t.

MS thinks I should be using its own «safer» version scanf_s which is even tricker to use and IMO no safer at all – because it is not a like-for-like replacement but takes different arguments, and so it is easy to make mistakes in using it.

One consequent problem is the compiler issues a warning for every use of scanf (and some other functions) which obscures other warnings. I deal with it as advised by adding a #define before the first library header inclusion.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

There are other matters which MS warns about too, and I actually place three #defines at the start of each file:

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE  
#define _CRT_NONSTDC_NO_DEPRECATE

#include <stdio.h>

And now the relevant warnings are easy to see.

answered Sep 19, 2019 at 7:42

Weather Vane's user avatar

Weather VaneWeather Vane

33.2k7 gold badges36 silver badges56 bronze badges

2

From documentation of scanf() (e.g. https://en.cppreference.com/w/c/io/fscanf)

Return value
1-3) Number of receiving arguments successfully assigned (which may be zero in case a matching failure occurred before the first receiving argument was assigned), or EOF if input failure occurs before the first receiving argument was assigned.

You are ignoring that return value.

Replace

scanf("%d", &age);

by

int NofScannedArguments=0; /* Number of arguments which were
successfully filled by the most recent call to scanf() */

/* ...  do above once, at the start of your function */

NofScannedArguments= scanf("%d", &age);

/* check the return value to find out whether scanning was successful */
if(NofScannedArguments!=1) /* should be one number */
{
    exit(EXIT_FAILURE); /* failure, assumptions of program are not met */
}

… to find out whether scanning succeeded.
Not doing so is a bad idea and worth the warning you got.

In case you want to handle failures more gracefully, e.g. prompt the user again,
use a loop and read http://sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html about the pitfalls you may encounter.
I am not saying you should NOT use scanf, the article explains a lot about using scanf, while trying to convince you not to.

answered Sep 19, 2019 at 6:05

Yunnosch's user avatar

YunnoschYunnosch

25.8k9 gold badges42 silver badges54 bronze badges

4

Using C++ functions for input is SO much easier. Instead of scanf and printf one could use cin and cout as the following demonstrates:

#include <iostream>  // for cin and cout use

int main()
{
    int zones;

    std::cout << "Enter zones" << std::endl;  // endl is similar to n
    std::cin >> zones;
    std::cout << "Your zones is " << zones << std::endl;
}

answered Jun 9, 2021 at 14:40

Ken's user avatar

2

That’s a nice warning, since ignoring the return value of fscanf() could lead to undefined behavior. I suppose you can’t silence that warning unless you handle the return value, that’s very easy

if (fscanf(fp, "%*d%*d%d%d%d", &z, &e, &a) == 3)
    usevalues(z, e, a);
else
    reportproblem_do_not_use_z_e_or_a();

Warnings are good teachers of how to correctly use functions, you should never ignore fscanf()‘s return value, and more importantly you should never ignore/silence a warning. If the compiler is warning about something, it must be because you are doing something wrong1.

In this case, if you don’t check the value and proceed to use z, e or a their content might be undefined at the moment of reading them and some unexpected things will occur.

The worst part is that it will be very difficult to find out that, these unexpected things (calculations for example) are happening because you DID NOT CHECK fscanf()‘s return value.


1Except in very few situations, where you intentionally do something that will trigger a warning. But those kinds of situations only happen when you are a very experienced c programmer.

That’s a nice warning, since ignoring the return value of fscanf() could lead to undefined behavior. I suppose you can’t silence that warning unless you handle the return value, that’s very easy

if (fscanf(fp, "%*d%*d%d%d%d", &z, &e, &a) == 3)
    usevalues(z, e, a);
else
    reportproblem_do_not_use_z_e_or_a();

Warnings are good teachers of how to correctly use functions, you should never ignore fscanf()‘s return value, and more importantly you should never ignore/silence a warning. If the compiler is warning about something, it must be because you are doing something wrong1.

In this case, if you don’t check the value and proceed to use z, e or a their content might be undefined at the moment of reading them and some unexpected things will occur.

The worst part is that it will be very difficult to find out that, these unexpected things (calculations for example) are happening because you DID NOT CHECK fscanf()‘s return value.


1Except in very few situations, where you intentionally do something that will trigger a warning. But those kinds of situations only happen when you are a very experienced c programmer.

VdiSn

0 / 0 / 0

Регистрация: 11.09.2022

Сообщений: 1

1

11.09.2022, 12:14. Показов 3731. Ответов 2

Метки нет (Все метки)


При scanf выдает ошибку, при csanf_s ошибки нет, можете разъяснить что не так в записи(Предупреждение C6031 Возвращаемое значение пропущено: «scanf»)

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <iostream>
#include <math.h>
 
int main() {
    setlocale(LC_ALL, "Russian");
    int x1, y1, x2, y2, stor_x = 0, stor_y = 0, P = 0, S = 0;
    printf("Введите значение х точки А = ");
    scanf("%d", &x1);
    printf("Введите значение y точки А = ");
    scanf("%d", &y1);
    printf("Введите значение х точки B = ");
    scanf("%d", &x2);
    printf("Введите значение y точки B = ");
    scanf("%d", &y2);
    stor_x = abs(x1 - x2);
    stor_y = abs(y1 - y2);
    P = (2 * stor_x) + (2 * stor_y);
    S = stor_x * stor_y;
    printf("P = %d nS = %d", P, S);
    return 0;
 
 
}

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

11.09.2022, 12:14

Ответы с готовыми решениями:

Структура в List<>, «Не удалось изменить возвращаемое значение»
Всем привет.
namespace
{
struct STRUCT
{
internal float a;

Не удалось изменить возвращаемое значение «Transform.position», т.к. оно не является переменной
Не удалось изменить возвращаемое значение &quot;Transform.position&quot;, т.к. оно не является переменной….

Известны сорта роз, выращиваемых тремя цветоводами: «Анжелика», «Виктория», «Гагарин», «Ave Maria», «Катарина», «Юбилейн
Известны сорта роз, выращиваемых тремя цветоводами: &quot;Анжелика&quot;, &quot;Виктория&quot;, &quot;Гагарин&quot;, &quot;Ave…

Дан массив строк: «red», «green», «black», «white», «blue». Запишите в файл элементы массива построчно (в новой строке)
пишу так но не помогает:

static void Main(string args)
{
string…

2

Эксперт .NET

16739 / 12492 / 3283

Регистрация: 17.09.2011

Сообщений: 20,719

11.09.2022, 12:38

2

Цитата
Сообщение от VdiSn
Посмотреть сообщение

Ошибка C6031

Цитата
Сообщение от VdiSn
Посмотреть сообщение

Предупреждение C6031

Так ошибка или предупреждение?

scanf возвращает значение, которое вы игнорируете — об этом компилятор и предупреждает.



0



zss

Модератор

Эксперт С++

12624 / 10123 / 6096

Регистрация: 18.12.2011

Сообщений: 27,157

11.09.2022, 17:45

3

У меня Ваш код никаких предупреждений не выдает.

Не в тему, но

Цитата
Сообщение от VdiSn
Посмотреть сообщение

#include <iostream>

каким боком здесь?
Только потому, что забыли добавить

C
1
#include <locale.h>

??????????????????
Сомнительное решение
1. Зачем сишную программу превращать в C++
2. В принципе, не обязан iostream подключать locale.h. Просто повезло….



0



что возвращает fscanf при чтении данных в файле. Например,

int number1, number2, number3, number4, c;

c = fscanf (spFile, "%d", &number1);
//c will be 1 in this case.

c = fscanf (spFile, "%d %d %d %d", &number1, &number1, &number3, &number4);
//in this case, c will return 4.

Я просто хочу знать, почему он возвращает такие значения в зависимости от числа аргументов.

5 ответов


С manpage для семейства Xscanf функции:

после успешного завершения эти функции возвращают число
успешно сопоставлены и назначены входные элементы
; это число может быть равно нулю
в случае ранней ошибки сопоставления. Если вход заканчивается раньше
первый соответствуя отказ или преобразование, EOF будут возвращены. Если
возникает ошибка чтения, устанавливается индикатор ошибки для потока, EOF
должен быть возвращен, и errno будет установлен в
укажите ошибку

Итак, ваш первый вызов fscanf возвращает 1, потому что один элемент ввода (&number1) был успешно сопоставлен со спецификатором формата %d. Ваш второй звонок в fscanf возвращает 4, потому что все 4 аргумента были сопоставлены.


цитирую cplusplus.com .

при успешном выполнении функция возвращает количество элементов аргумента
список успешно заполнен. Это число может соответствовать ожидаемому числу
элементы или быть меньше (даже ноль) из-за сбоя сопоставления, чтения
ошибки или достижения конца файла.

Если происходит ошибка чтения или конец файла достигается в то время
чтение, правильной индикатор установлен (feof или ferror). И, если
происходит до того, как какие-либо данные могут быть успешно прочитаны, возвращается EOF.

— EDIT—

Если вы намерены определить количество байтов, прочитанных в строке.

int bytes;
char str[80];
fscanf (stdin, "%s%n",str,&bytes);
printf("Number of bytes read = %d",bytes);

3

автор: Barath Ravikumar


с руководство страницы:

*эти функции возвращают количество успешно сопоставленных и назначенных входных элементов, которое может быть меньше, чем предусмотрено, или даже равно нулю в случае раннего сбоя сопоставления. *

следовательно, 1-й возвращает 1, если можно прочитать одно целое число из файла, 2-й возвращает 4, если можно прочитать 4 целых числа из файла.


это очень прямой вопрос, и Чарльз и Эд правильно ответили на него до меня. Но они не упомянули, где вы должны искать такие вещи в следующий раз, когда вы застряли.

первый вопрос —
fscanf принадлежит к семейству формируемых функций ввода (сканирования), которые должны считывать ввод и сообщать некоторую информацию о данных, считываемых как байты или количество элементов(адресов переменных), которые получили соответствующий ввод и имели успешным заданием.

здесь fscanf должен проверить совпадения во входном файле со строкой формата, указанной в вызове функции, и, соответственно, назначить переменную — адрес (в порядке их расположения) со значением, и после завершения она вернет общее количество успешных назначений, которые она сделала. отсюда и результат 1 и 4 (если была оказана должным образом).

вторая часть: где искать ? —
что ж описанные детали для такой функции легко найти на страницах руководства или posix doc, если вы обратитесь к одному.

Если вы заметили, предыдущие два ответа также содержат небольшие выдержки из man-страниц .

надеюсь, что это помогает.


возвращаемое значение не зависит от количества аргументов fscanf ,Это зависит от количества значений успешно сканируются fscanf.


Мне жаль, что я задаю этот вопрос (потому что в Интернете так много об этом), но я должен спросить об этом:

Упражнение включает чтение из файла со списком студентов (запись содержит: имя, фамилию и серийный номер). Я уже создал документ и состоял из 13 строк, но когда я пишу на терминале ./a.out, вывод представляет собой список из 13 строк этого типа: (null) (null) (null)

Код:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#define EOF (-1)
#define BUF 100

typedef struct stud{
char *surname;
char *name;
char *serial;
} student;

int main(void){
FILE *fd;
int n = BUF;
int k = 0;
int i = 0;
int ret;
char *s = malloc(BUF * sizeof(char));
if((fd = fopen("registry_office_students.txt","r")) == NULL){
perror("error opening file");
return -1;
}
while(fgets(s,n,fd)!=NULL){
k++;
}
student *a = malloc(k*sizeof(student));
rewind(fd);
ret = fscanf(fd, "%s, %s, %s", a[i].surname, a[i].name, a[i].serial);
while(fscanf(fd, "%s, %s, %s", a[i].surname, a[i].name, a[i].serial) == ret){
i++;
}
for(i=0;i<k;i++){
printf("%s, %s, %s n", a[i].surname, a[i].name, a[i].serial);
}
fclose(fd);
return 0;
}

Я снова прошу прощения и надеюсь на правильный ответ, спасибо.

The man page say:

The value EOF is returned if the end of input is reached before
either the first successful conversion or a matching failure occurs.
EOF is also returned if a read error occurs, in which case the error
indicator for the stream (see ferror(3)) is set, and errno is set to
indicate the error.

This means that you can check against EOF:

#include<stdio.h>

int main(void){
    int a;
    printf("Please give the value of A: ");

    if(scanf("%d",&a) != EOF){
        printf("nThe value of A ist%dn",a);
    }

    return 0;
}

Or:

#include<stdio.h>
#include <errno.h>
#include<string.h>

int main(void){
    int a, errnum = errno;
    printf("Please give the value of A: ");

    if(scanf("%d",&a) == EOF){
        fprintf(stderr, "Value of errno: %dn", errno);
        perror("Error printed by perror");
        fprintf(stderr, "Error opening file: %sn", strerror( errnum ));
    }

    printf("nThe value of A ist%dn",a);
    return 0;
}

This applies for:

scanf, fscanf, sscanf, vscanf, vsscanf, vfscanf — input format con‐
version

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Возвратившись домой он сразу оказался под неусыпным оком матери ошибка
  • Водонагреватель поларис коды ошибок