С6031 visual studio ошибка

Kartoshkas

0 / 0 / 0

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

Сообщений: 1

1

04.10.2021, 18:40. Показов 3504. Ответов 3

Метки micrisift visual studio 2019, си для начинающих (Все метки)


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

Я буквально сегодня, по какому-то видео уроку начала изучать С, вот то, что создано мной на данном этапе

C
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
 
        int main() {
 
    float x, y, res;
    scanf("%f", &x);
    scanf("%f", &y);
 
    res = x / y;
    printf("Result: %.2f\n", res);
        return 0;
}

Пишу я в Microsoft Visual studio, при запуске этого кода не даёт ввести чисел. После закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’.
Когда вбиваю код в онлайн компилятор — там всё в порядке.

Подскажите, пожалуйста, в чём может быть проблема?



0



Модератор

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

4723 / 2733 / 1451

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

Сообщений: 5,044

Записей в блоге: 1

04.10.2021, 19:11

2

Kartoshkas, заменяйте функцию scanf() на scanf_s()



0



Вездепух

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

11087 / 6054 / 1651

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

Сообщений: 15,183

04.10.2021, 19:34

3

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

при запуске этого кода не даёт ввести чисел.

Вы что-то выдумываете.

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

после закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’.

Что такое «предупреждения после закрытия консоли»???

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

Подскажите, пожалуйста, в чём может быть проблема?

Сформулируйте осмысленное описание проблемы. Пока что ничего не понятно.



0



easybudda

Модератор

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

12225 / 7357 / 1730

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

Сообщений: 13,462

04.10.2021, 20:11

4

Лучший ответ Сообщение было отмечено Kartoshkas как решение

Решение

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

заменяйте функцию scanf() на scanf_s()

…и получите обратную историю: M$VS пропустит (не факт — ругань на игнорирование результата, возвращённого scanf), а онлайн компилятор скорее всего скажет «опаньки».
Про *_s функции здесь споры уже не раз были. И как бы ни ликовали адепты M$ по поводу впихивания в стандарт, кроме мелкомягкого cl так и не нашлось компилятора, который бы их поддерживал.

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

Подскажите, пожалуйста, в чём может быть проблема?

Проблема в заморочках компилятора от Майкрософт, про которые пишут далеко не во всех книгах по языку С, поскольку к языку это никак не относится.
Ничего больше не меняя, самой первой строкой вставьте

C
1
#define _CRT_SECURE_NO_WARNINGS

Не поможет — пишите, там ещё есть танцы с бубнами…



2



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

Я использую версию 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>

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

title description ms.date f1_keywords helpviewer_keywords ms.assetid

Warning C6031

Describes C++ Code Analysis warning C6031 and how to resolve it.

10/04/2022

C6031

RETVAL_IGNORED_FUNC_COULD_FAIL

__WARNING_RETVAL_IGNORED_FUNC_COULD_FAIL

C6031

59e1ef0a-b3ca-4ffa-bcb3-ad2bd22ece22

Warning C6031

Return value ignored: ‘called-function‘ could return unexpected value

Remarks

Warning C6031 indicates the caller doesn’t check a function’s return value for failure. Depending on which function is being called, this defect can lead to seemingly random program misbehavior. That includes crashes and data corruptions in error conditions or low-resource situations.

In general, it isn’t safe to assume that calls to functions requiring disk, network, memory, or other resources will succeed. The caller should always check the return value and handle error cases appropriately. Also consider using the _Must_inspect_result_ annotation, which checks that the value is examined in a useful way.

Code analysis name: RETVAL_IGNORED_FUNC_COULD_FAIL

Example

The following code generates warning C6031:

#include <stdio.h>
void f( )
{
    fopen( "test.c", "r" ); // C4996, C6031 return value ignored
    // code ...
}

To correct this warning, check the return value of the function as shown in the following code:

#include <stdio.h>
void f( )
{
    FILE *stream;
    if ( (stream = fopen( "test.c", "r" )) == NULL )
        return;
    // code ...
}

The following code uses safe function fopen_s to correct this warning:

#include <stdio.h>
void f( )
{
    FILE *stream;
    errno_t err;

    if ( (err = fopen_s( &stream, "test.c", "r" )) !=0 )
    {
        // code ...
    }
}

This warning is also generated if the caller ignores the return value of a function annotated with the _Check_return_ property as shown in the following code.

#include <sal.h>
_Check_return_ bool func();

void test_f()
{
    func(); //  Warning C6031
}

To correct the previous warning, check the return value as shown in the following code:

#include <sal.h>
_Check_return_ bool func();

void test_f()
{
    if ( func() ) {
        // code ...
    }
}

In cases where it’s necessary to ignore the return value of a function, assign the returned value to std::ignore. Assigning to std::ignore clearly indicates developer intent and helps in future code maintenance.

#include <tuple>
#include <ctime>
#include <stdio.h>
void f()
{
    std::srand(static_cast(std::time(nullptr))); // set initial seed value to system clock
    std::ignore = std::rand(); // Discard the first result as the few random results are always small.
    // ... 
}

See also

fopen_s, _wfopen_s
Using SAL Annotations to reduce code defects

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.4k7 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 badges43 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

I am very new and only starting learning how to code a few weeks ago. I downloaded visual studios and tried to use it as an editor and C compiler. I made a program and tried to compile it but it wouldn’t due to this C6031 («Return value ignored: ‘scanf’) warning. I tried compiling it on a C compiler online and it worked. Not sure how to fix this. Is it a problem with visual studios (v 2019)? This is my code.

#include<stdio.h>
#include<math.h>
int main(void)
{
    // Define variables
double x, answer;
    // Define the value we will find the sin of
printf("Enter a value for x between (0, 1): ");
    scanf("%lf", &x);
    // Calculate the sin of value
    answer = sin(x);
    if ((x >= 0) && (x <= 1)) {
            // Display answer
        printf("nThe sine of %lf is %lf", x, answer); }
    else
{
        printf("Value is not within (0, 1) range.");
}
return 0;
}

#c #visual-studio #visual-studio-2019 #compiler-warnings

#c #visual-studio #visual-studio-2019 #компилятор-предупреждения

Вопрос:

Я очень новичок и только начал изучать, как кодировать несколько недель назад. Я загрузил visual studios и попытался использовать его в качестве редактора и компилятора C. Я создал программу и попытался ее скомпилировать, но это не удалось из-за этого предупреждения C6031 («Возвращаемое значение игнорируется: ‘scanf’). Я попытался скомпилировать его с помощью онлайн-компилятора C, и это сработало. Не уверен, как это исправить. Это проблема с visual studios (v 2019)? Это мой код.

 #include<stdio.h>
#include<math.h>
int main(void)
{
    // Define variables
double x, answer;
    // Define the value we will find the sin of
printf("Enter a value for x between (0, 1): ");
    scanf("%lf", amp;x);
    // Calculate the sin of value
    answer = sin(x);
    if ((x >= 0) amp;amp; (x <= 1)) {
            // Display answer
        printf("nThe sine of %lf is %lf", x, answer); }
    else
{
        printf("Value is not within (0, 1) range.");
}
return 0;
}
 

Комментарии:

1. C6031 предупреждает, что scanf возвращает » количество успешно назначенных аргументов приема «, но код игнорирует это возвращаемое значение и продолжает использовать x , не проверив, действительно ли оно было назначено.

2. Как вы должны обнаруживать и обрабатывать ошибки при вводе, если вы игнорируете scanf() возвращаемое значение? Компилятор пытается помочь вам не стрелять себе в ногу.

Kartoshkas

0 / 0 / 0

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

Сообщений: 1

1

04.10.2021, 18:40. Показов 2533. Ответов 3

Метки micrisift visual studio 2019, си для начинающих (Все метки)


Я буквально сегодня, по какому-то видео уроку начала изучать С, вот то, что создано мной на данном этапе

C
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
 
        int main() {
 
    float x, y, res;
    scanf("%f", &x);
    scanf("%f", &y);
 
    res = x / y;
    printf("Result: %.2fn", res);
        return 0;
}

Пишу я в Microsoft Visual studio, при запуске этого кода не даёт ввести чисел. После закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’.
Когда вбиваю код в онлайн компилятор — там всё в порядке.

Подскажите, пожалуйста, в чём может быть проблема?

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

0

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

4209 / 2425 / 1317

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

Сообщений: 4,576

Записей в блоге: 1

04.10.2021, 19:11

2

Kartoshkas, заменяйте функцию scanf() на scanf_s()

0

Вездепух

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

10421 / 5693 / 1550

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

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

04.10.2021, 19:34

3

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

при запуске этого кода не даёт ввести чисел.

Вы что-то выдумываете.

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

после закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’.

Что такое «предупреждения после закрытия консоли»???

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

Подскажите, пожалуйста, в чём может быть проблема?

Сформулируйте осмысленное описание проблемы. Пока что ничего не понятно.

0

easybudda

Модератор

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

11649 / 7161 / 1700

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

Сообщений: 13,117

04.10.2021, 20:11

4

Лучший ответ Сообщение было отмечено Kartoshkas как решение

Решение

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

заменяйте функцию scanf() на scanf_s()

…и получите обратную историю: M$VS пропустит (не факт — ругань на игнорирование результата, возвращённого scanf), а онлайн компилятор скорее всего скажет «опаньки».
Про *_s функции здесь споры уже не раз были. И как бы ни ликовали адепты M$ по поводу впихивания в стандарт, кроме мелкомягкого cl так и не нашлось компилятора, который бы их поддерживал.

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

Подскажите, пожалуйста, в чём может быть проблема?

Проблема в заморочках компилятора от Майкрософт, про которые пишут далеко не во всех книгах по языку С, поскольку к языку это никак не относится.
Ничего больше не меняя, самой первой строкой вставьте

C
1
#define _CRT_SECURE_NO_WARNINGS

Не поможет — пишите, там ещё есть танцы с бубнами…

2

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

As @SteveSummit indicates in a comment, most C implementations have a mechanism to identify functions whose return value should not be ignored.

C itself (as defined by the C standard) has always allowed a caller to ignore the return value of a function. It even allows a function declared with a return value type to not return any value as long as all callers ignore the return value.

However, that permissiveness does not generally lead to good programming practice. In some cases, it is very likely that ignoring the return value of a function will lead to a bug. scanf is considered to be such a function, so the authors of standard libraries tend to mark scanf as requiring that the return value be used.

There is no standard way to mark a function as requiring use of their return values. In GCC and Clang, this is done using the attribute warn_unused_result:

int fn (int a) __attribute__ ((warn_unused_result));

(See the GCC documentation for the warn_unused_result function attribute and how to turn off the warning (not recommended): the `-Wno-unused-result.)

In MSVC, it’s done with the _Check_return_ macro, found in sal.h:

#include <sal.h>
_Check_return_ int fn (int a);

(See the Visual Studio docs for error C6031 and this documenation on the Source Annotation Library (sal).)

There are good reasons not to ignore the return value of any library function which uses the return value to indicate failure, including many standard library functions which do input or output. Ignoring input or output failure can lead to problems, but the problems are more evident when ignoring input failure because that can lead to the use of uninitialised values, which in turn can lead to Undefined Behaviour. That is certainly the case for scanf: ignoring its return value means that your program will not respond correctly to malformed input, which is almost certainly a bug.

Ignoring the failure of output functions will sometimes mean that the user is not warned about failure to save persistent data. That can be serious, and it may well be that some action needs to be taken to save that data. But in other cases, the error simply means that the user didn’t see some logging message and most likely will not see future logging messages either. This might not be considered important.

As @SteveSummit indicates in a comment, most C implementations have a mechanism to identify functions whose return value should not be ignored.

C itself (as defined by the C standard) has always allowed a caller to ignore the return value of a function. It even allows a function declared with a return value type to not return any value as long as all callers ignore the return value.

However, that permissiveness does not generally lead to good programming practice. In some cases, it is very likely that ignoring the return value of a function will lead to a bug. scanf is considered to be such a function, so the authors of standard libraries tend to mark scanf as requiring that the return value be used.

There is no standard way to mark a function as requiring use of their return values. In GCC and Clang, this is done using the attribute warn_unused_result:

int fn (int a) __attribute__ ((warn_unused_result));

(See the GCC documentation for the warn_unused_result function attribute and how to turn off the warning (not recommended): the `-Wno-unused-result.)

In MSVC, it’s done with the _Check_return_ macro, found in sal.h:

#include <sal.h>
_Check_return_ int fn (int a);

(See the Visual Studio docs for error C6031 and this documenation on the Source Annotation Library (sal).)

There are good reasons not to ignore the return value of any library function which uses the return value to indicate failure, including many standard library functions which do input or output. Ignoring input or output failure can lead to problems, but the problems are more evident when ignoring input failure because that can lead to the use of uninitialised values, which in turn can lead to Undefined Behaviour. That is certainly the case for scanf: ignoring its return value means that your program will not respond correctly to malformed input, which is almost certainly a bug.

Ignoring the failure of output functions will sometimes mean that the user is not warned about failure to save persistent data. That can be serious, and it may well be that some action needs to be taken to save that data. But in other cases, the error simply means that the user didn’t see some logging message and most likely will not see future logging messages either. This might not be considered important.

#c #visual-studio #visual-studio-2019 #compiler-warnings

#c #visual-studio #visual-studio-2019 #компилятор-предупреждения

Вопрос:

Я очень новичок и только начал изучать, как кодировать несколько недель назад. Я загрузил visual studios и попытался использовать его в качестве редактора и компилятора C. Я создал программу и попытался ее скомпилировать, но это не удалось из-за этого предупреждения C6031 («Возвращаемое значение игнорируется: ‘scanf’). Я попытался скомпилировать его с помощью онлайн-компилятора C, и это сработало. Не уверен, как это исправить. Это проблема с visual studios (v 2019)? Это мой код.

 #include<stdio.h>
#include<math.h>
int main(void)
{
    // Define variables
double x, answer;
    // Define the value we will find the sin of
printf("Enter a value for x between (0, 1): ");
    scanf("%lf", amp;x);
    // Calculate the sin of value
    answer = sin(x);
    if ((x >= 0) amp;amp; (x <= 1)) {
            // Display answer
        printf("nThe sine of %lf is %lf", x, answer); }
    else
{
        printf("Value is not within (0, 1) range.");
}
return 0;
}
 

Комментарии:

1. C6031 предупреждает, что scanf возвращает » количество успешно назначенных аргументов приема «, но код игнорирует это возвращаемое значение и продолжает использовать x , не проверив, действительно ли оно было назначено.

2. Как вы должны обнаруживать и обрабатывать ошибки при вводе, если вы игнорируете scanf() возвращаемое значение? Компилятор пытается помочь вам не стрелять себе в ногу.

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

26k9 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

title description ms.date f1_keywords helpviewer_keywords ms.assetid

Warning C6031

Describes C++ Code Analysis warning C6031 and how to resolve it.

10/04/2022

C6031

RETVAL_IGNORED_FUNC_COULD_FAIL

__WARNING_RETVAL_IGNORED_FUNC_COULD_FAIL

C6031

59e1ef0a-b3ca-4ffa-bcb3-ad2bd22ece22

Warning C6031

Return value ignored: ‘called-function‘ could return unexpected value

Remarks

Warning C6031 indicates the caller doesn’t check a function’s return value for failure. Depending on which function is being called, this defect can lead to seemingly random program misbehavior. That includes crashes and data corruptions in error conditions or low-resource situations.

In general, it isn’t safe to assume that calls to functions requiring disk, network, memory, or other resources will succeed. The caller should always check the return value and handle error cases appropriately. Also consider using the _Must_inspect_result_ annotation, which checks that the value is examined in a useful way.

Code analysis name: RETVAL_IGNORED_FUNC_COULD_FAIL

Example

The following code generates warning C6031:

#include <stdio.h>
void f( )
{
    fopen( "test.c", "r" ); // C4996, C6031 return value ignored
    // code ...
}

To correct this warning, check the return value of the function as shown in the following code:

#include <stdio.h>
void f( )
{
    FILE *stream;
    if ( (stream = fopen( "test.c", "r" )) == NULL )
        return;
    // code ...
}

The following code uses safe function fopen_s to correct this warning:

#include <stdio.h>
void f( )
{
    FILE *stream;
    errno_t err;

    if ( (err = fopen_s( &stream, "test.c", "r" )) !=0 )
    {
        // code ...
    }
}

This warning is also generated if the caller ignores the return value of a function annotated with the _Check_return_ property as shown in the following code.

#include <sal.h>
_Check_return_ bool func();

void test_f()
{
    func(); //  Warning C6031
}

To correct the previous warning, check the return value as shown in the following code:

#include <sal.h>
_Check_return_ bool func();

void test_f()
{
    if ( func() ) {
        // code ...
    }
}

In cases where it’s necessary to ignore the return value of a function, assign the returned value to std::ignore. Assigning to std::ignore clearly indicates developer intent and helps in future code maintenance.

#include <tuple>
#include <ctime>
#include <stdio.h>
void f()
{
    std::srand(static_cast(std::time(nullptr))); // set initial seed value to system clock
    std::ignore = std::rand(); // Discard the first result as the few random results are always small.
    // ... 
}

See also

fopen_s, _wfopen_s
Using SAL Annotations to reduce code defects

При объявлении scanf, строки кода подчёркиваются желтой волнистой линией. Как ни старался решить эту проблему, ничего не выходит.

#include <stdio.h>

int main(){
  float x, y, res;
  scanf("%f", &x);
  scanf("%f", &y);
  res = x / y;
  printf("Result: %.2fn", res);
  return 0;
}

Harry's user avatar

Harry

215k15 золотых знаков117 серебряных знаков228 бронзовых знаков

задан 22 июн 2022 в 15:02

Courier Six's user avatar

3

Попробуйте переписать так:

#include <stdio.h>

int main(){
  float x, y, res;
  if (scanf("%f", &x) != 1) return 1;
  if (scanf("%f", &y) != 1) return 1;
  res = x / y;
  printf("Result: %.2fn", res);
  return 0;
}

ответ дан 22 июн 2022 в 18:47

Harry's user avatar

HarryHarry

215k15 золотых знаков117 серебряных знаков228 бронзовых знаков

Kartoshkas

0 / 0 / 0

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

Сообщений: 1

1

04.10.2021, 18:40. Показов 3276. Ответов 3

Метки micrisift visual studio 2019, си для начинающих (Все метки)


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

Я буквально сегодня, по какому-то видео уроку начала изучать С, вот то, что создано мной на данном этапе

C
1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
 
        int main() {
 
    float x, y, res;
    scanf("%f", &x);
    scanf("%f", &y);
 
    res = x / y;
    printf("Result: %.2fn", res);
        return 0;
}

Пишу я в Microsoft Visual studio, при запуске этого кода не даёт ввести чисел. После закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’.
Когда вбиваю код в онлайн компилятор — там всё в порядке.

Подскажите, пожалуйста, в чём может быть проблема?

0

Модератор

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

4696 / 2709 / 1445

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

Сообщений: 4,997

Записей в блоге: 1

04.10.2021, 19:11

2

Kartoshkas, заменяйте функцию scanf() на scanf_s()

0

Вездепух

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

10987 / 5970 / 1630

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

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

04.10.2021, 19:34

3

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

при запуске этого кода не даёт ввести чисел.

Вы что-то выдумываете.

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

после закрытия консоли в предупреждениях C6031, return value ignored: ‘scanf’.

Что такое «предупреждения после закрытия консоли»???

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

Подскажите, пожалуйста, в чём может быть проблема?

Сформулируйте осмысленное описание проблемы. Пока что ничего не понятно.

0

easybudda

Модератор

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

11908 / 7281 / 1722

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

Сообщений: 13,328

04.10.2021, 20:11

4

Лучший ответ Сообщение было отмечено Kartoshkas как решение

Решение

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

заменяйте функцию scanf() на scanf_s()

…и получите обратную историю: M$VS пропустит (не факт — ругань на игнорирование результата, возвращённого scanf), а онлайн компилятор скорее всего скажет «опаньки».
Про *_s функции здесь споры уже не раз были. И как бы ни ликовали адепты M$ по поводу впихивания в стандарт, кроме мелкомягкого cl так и не нашлось компилятора, который бы их поддерживал.

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

Подскажите, пожалуйста, в чём может быть проблема?

Проблема в заморочках компилятора от Майкрософт, про которые пишут далеко не во всех книгах по языку С, поскольку к языку это никак не относится.
Ничего больше не меняя, самой первой строкой вставьте

C
1
#define _CRT_SECURE_NO_WARNINGS

Не поможет — пишите, там ещё есть танцы с бубнами…

2

When running the scanf function in Visual Studio 2019, the following problems are encountered:

Solution:

method 1:

Add code at the top of the file:#pragma warning(disable:4996)

Method 2:

Right clickIn projectSource code(main.c), openAttributesColumn>Configuration properties>C/C++>All options,willSDL checkTono,save

Method 3:

willscanfToscanf_s

The above three methods are all Baidu, the first two of which are effective in the pro-test, and the third method is still wrong.

The test source program comes fromNovice Tutorial.

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

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

    printf("Please enter an integer value:");
    scanf("%d",&a);
    assert(a >= 10);
    printf("The integer entered is: %dn", a);

    printf("Please enter a string: ");
    scanf("%s", str);
    assert(str != NULL);
    printf("The input string is: %sn",&str);

    return(0);
}

Learning link:
The usage of assert
C language scanf function usage complete guideNot seen

При запуске функции 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Не видно

Понравилась статья? Поделить с друзьями:
  • С56е ошибка пежо 308
  • С6020 ошибка kyocera 2035
  • С6 неисправимые ошибки секторов что делать
  • С4ева341 ошибка принтера
  • С428 ошибка мерседес