Возвращаемое значение пропущено 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.7k7 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.9k9 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

dopaminos

0 / 0 / 0

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

Сообщений: 24

1

05.04.2022, 10:59. Показов 918. Ответов 8

Метки c++, си (Все метки)


Студворк — интернет-сервис помощи студентам

Пишу программу, которая записывает номер зачётной книжки в файл, чтобы было, т.с, выбрать тип шифрования и им собственно шифровать информацию, которая поступит через консоль в source (source.txt) ((ещё не дописал сами алгоритмы шифрования, в процессе)), но все scanf/fscanf игнорируются.

В чём я допустил ошибку?

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
#include <iostream>;
#include <fstream>;
#include <string>;
#pragma warning(disable: 4996);
char record_book_number[7] = "";
    char cipher_type[1];
    char source_info[INT_MAX];
    char ciphered_info[INT_MAX];
 
int main() {
    setlocale(LC_ALL, "Russian");
    FILE* config = fopen("D:/Docs/rec_book_number.txt", "w");
    FILE* source = fopen("D:/Docs/source.txt", "w");
    if (!config || !source)
    { printf("Нельзя открыть rec_book_number.txt"); return 1; }
    printf("Введите номер зачётной книжкиn");
    fscanf(config, "%cn", record_book_number);
    printf("Select cipher type:n 1. Caesarn 2. Vigenerennn");
    scanf("%c", &cipher_type[1]);
    printf("Вы выбрали тип шифрования № %с n", cipher_type);
    fopen("source.txt", "w");
    printf("Input line to cipher: n");
    fscanf(source, "%sn", source_info);
    system("pause");
}



0



Programming

Эксперт

94731 / 64177 / 26122

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

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

05.04.2022, 10:59

8

677 / 548 / 134

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

Сообщений: 1,543

05.04.2022, 11:36

2

Аргумент scanf и fscanf — указатель. Соответственно, & везде забыли.

Добавлено через 6 минут
А, нет, это была глупость.



0



Вездепух

Эксперт CЭксперт С++

10908 / 5905 / 1613

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

Сообщений: 14,841

05.04.2022, 12:11

3

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

#include <iostream>;

Что здесь делает ;?

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

fscanf(config, «%cn», record_book_number);

Что делает n в форматной строке fscanf?

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

scanf(«%c», &cipher_type[1]);

Распространенные ошибки

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

но все scanf/fscanf игнорируются.

Это какие-то выдумки. Что значит «игнорируются»?



0



0 / 0 / 0

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

Сообщений: 24

05.04.2022, 12:19

 [ТС]

4

Цитата
Сообщение от TheCalligrapher

Это какие-то выдумки. Что значит «игнорируются»?

Предупреждение компилятора C6031: Возвращаемое значение пропущено



0



Вездепух

Эксперт CЭксперт С++

10908 / 5905 / 1613

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

Сообщений: 14,841

05.04.2022, 12:22

5

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

Предупреждение компилятора C6031: Возвращаемое значение пропущено

Не понял. Так «scanf игнорируются» или «предупреждение компилятора»? О чем именно вопрос?



0



0 / 0 / 0

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

Сообщений: 24

05.04.2022, 12:28

 [ТС]

6

Цитата
Сообщение от TheCalligrapher

О чем именно вопрос?

Об этом предупреждении, ведь из-за него программа неправльно работает.



0



Вездепух

Эксперт CЭксперт С++

10908 / 5905 / 1613

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

Сообщений: 14,841

05.04.2022, 18:18

7

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

Об этом предупреждении, ведь из-за него программа неправльно работает.

Нет, это предупреждение никакого отношения к неправильной работе программы не имеет.

Что такое «не удается ввести информацию» для точек «Введите номер зачётной книжки» и «Input line to cipher:», на которые вы нарисовали красные стрелочки? Не то значение читается из файла? Вы проверяли?

Что такое «неверная работа ввода» (кроме той ошибки, на которую я уже указал)?



0



0 / 0 / 0

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

Сообщений: 24

05.04.2022, 20:54

 [ТС]

8

Что такое «не удается ввести информацию»?

printf работает и линия «Введите номер зачётной книжки» выводится, а scanf нет, и информацию не удается ввести

Что такое «неверная работа ввода»?

Ввожу 1.
Правильный вывод: Вы выбрали тип шифрования № 1. Выводит № c



0



TheCalligrapher

Вездепух

Эксперт CЭксперт С++

10908 / 5905 / 1613

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

Сообщений: 14,841

06.04.2022, 02:10

9

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

rintf работает и линия «Введите номер зачётной книжки» выводится, а scanf нет, и информацию не удается ввести

Ничего не понял.

Какой scanf? У вас нет и никогда не было никакого scanf после «Введите номер зачётной книжки». У вас после «Введите номер зачётной книжки» стоит fscanf, а не scanf. Замечаете разницу? Вы сами читаете информацию из файла. Вы не хотите ничего «вводить», вы хотите читать из файла, как вы и написали в коде.

О чем речь тогда? Что такое «информацию не удается ввести»? Файл не читается?

Сколько можно задавать один и тот же вопрос?

Добавлено через 2 минуты

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

Правильный вывод: Вы выбрали тип шифрования № 1. Выводит № c

Так я же уже указал вам на ошибки. Что это такое

C
1
2
    scanf("%c", &cipher_type[1]);
    printf("Вы выбрали тип шифрования № %с n", cipher_type);

? Здесь написана бессмыслица. В обоих строчках. В scanf — выход за пределы массива. В printf — вообще неправильный аргумент, который при этом не связан с предыдущим scanf.



0



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.

Здесь слишком много, чтобы оставлять комментарии.

Я использую версию Visual C, но она никогда не жалуется на возвращаемое значение из scanfне используется. Что это делает, чтобы жаловаться, чтоscanfявляется небезопасным и не рекомендуется, если это не так.

MS думает, что мне следует использовать его собственную «более безопасную» версию scanf_s что еще сложнее в использовании, а ИМО вовсе не безопаснее — потому что это не аналогичная замена, но требует других аргументов, и поэтому при ее использовании легко сделать ошибки.

Одна из последующих проблем заключается в том, что компилятор выдает предупреждение при каждом использованииscanf(и некоторые другие функции), которые скрывают другие предупреждения. Я справляюсь с этим, как советую, добавляя#define перед первым включением заголовка библиотеки.

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>

Есть и другие вопросы, о которых предупреждает MS, и я на самом деле ставлю три #defines в начале каждого файла:

#define _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_DEPRECATE  
#define _CRT_NONSTDC_NO_DEPRECATE

#include <stdio.h>

И теперь соответствующие предупреждения легко увидеть.

При запуске функции scanf в Visual Studio 2019 возникают следующие проблемы:

Решение:

способ 1:

Добавьте код вверху файла:#pragma warning(disable:4996)

Способ 2:

Щелкните правой кнопкой мышиВ проектеИсходный код(main.c), открытьАтрибутыКолонка>Свойства конфигурации>C/C++>Все варианты,воляSDL проверкаЧтобынет,спасти

Способ 3:

воляscanfЧтобыscanf_s

Все три вышеуказанных метода относятся к Baidu, первые два из которых эффективны в про-тестировании, а третий метод по-прежнему неверен.

Исходная программа теста взята изУчебник для новичков.

//#pragma warning(disable:4996)
#include <assert.h>
#include <stdio.h>

int main()
{
    int a;
    char str[50];

    printf("Пожалуйста, введите целое число:");
    scanf("%d",&a);
    assert(a >= 10);
    printf("Введено целое число:% d  n", a);

    printf("Пожалуйста, введите строку:");
    scanf("%s", str);
    assert(str != NULL);
    printf("Строка ввода:% s  n",&str);

    return(0);
}

Ссылка на обучение:
Использование assert
Полное руководство по использованию функции scanf на языке CНе видно

Русские Блоги

Возвращаемое значение C6031 игнорируется: решение «scanf»

При запуске функции scanf в Visual Studio 2019 возникают следующие проблемы:

Решение:

способ 1:

Добавьте код вверху файла: #pragma warning(disable:4996)

Способ 2:

Щелкните правой кнопкой мышиВ проектеИсходный код(main.c), открытьАтрибутыКолонка>Свойства конфигурации>C/C++>Все варианты,воляSDL проверкаЧтобынет,спасти

Способ 3:

воляscanfЧтобыscanf_s

Все три вышеуказанных метода относятся к Baidu, первые два из которых эффективны в про-тестировании, а третий метод по-прежнему неверен.

После добавления
#define _CRT_SECURE_NO_WARNINGS
ничего не меняется.
А при использовании scanf_s, программа запускается но после ввода значения выкидывает такую ошибку:
dadd1062d568496b8a2b5a511177299f.png

  • Вопрос задан более трёх лет назад
  • 14212 просмотров
  • Facebook
  • Вконтакте
  • Twitter
  • Facebook
  • Вконтакте
  • Twitter
  • Facebook
  • Вконтакте
  • Twitter

Добавлять нужно в самом начале файла, до подключения любых заголовочных файлов.

И самое главное: у вас есть один char, в котором есть место для одного символа. При чтении в %s, сохранено будет как минимум два — символ и завершающий 0.

Предупреждение C6031 Возвращаемое значение пропущено: «scanf»

Не удалось изменить возвращаемое значение «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.

How to fix «return value ignored: ‘scanf'» code C6031 in visual studio

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!

3 Answers 3

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.

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

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

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

Упражнение включает чтение из файла со списком студентов (запись содержит: имя, фамилию и серийный номер). Я уже создал документ и состоял из 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;
}

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

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

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

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

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