Ошибка c6031 c

C6031 в Microsoft Visual Studio C (СИ) Решение и ответ на вопрос 2879601

Kartoshkas

0 / 0 / 0

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

Сообщений: 1

1

04.10.2021, 18:40. Показов 2667. Ответов 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Эксперт С++

4269 / 2474 / 1338

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

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

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

04.10.2021, 19:11

2

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



0



Вездепух

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

10452 / 5719 / 1556

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

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

04.10.2021, 19:34

3

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

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

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

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

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

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

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

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

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



0



easybudda

Модератор

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

11660 / 7173 / 1704

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

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

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



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.

Я использую следующий код для форматирования HRESULT сообщения и записи сообщения в файл, только если HRESULT является ошибкой.

Код компилируется и работает нормально, за исключением того, что я получаю следующее предупреждение компилятора:

Предупреждение C6031 Возвращаемое значение игнорируется: ‘wcsrchr’.

Я не хочу отключать предупреждение, но хочу его устранить, но я не могу понять, как это сделать? Вот минимальный компилируемый код:

// compile with: /Wall
#include <Windows.h>
#include <cwchar>       // std::wcsrchr
#include <comdef.h>     // _com_error
#include <iostream>     // std::cin

// Show only file name instead of full path wide version
#define __FILENAME__ (std::wcsrchr(TEXT(__FILE__), L'\') ? std::wcsrchr(TEXT(__FILE__), L'\') + 1 : TEXT(__FILE__))

// Writes a sprintf-formatted string to the logging file.
#define TRACE(...) DebugLogTrace(__VA_ARGS__)

// Log HRESULTs if failed.
#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr)) 
    { TRACE((TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage())); }

// Writes a sprintf-formatted string to the logging file.
void DebugLogTrace(PCTSTR format_string, ...) noexcept
{
    // implementation not important
}

int main()
{
      // generate example failure
      LOG_IF_FAILED(__FILENAME__, __LINE__, E_FAIL);

      std::cin.get();
      return 0;
}

Пример вывода файла для кода ошибки E_FAIL:

7:50:11 Неизвестная ошибка

1 ответ

Лучший ответ

Мне удалось отключить предупреждение, изменив:

#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr)) 
    { TRACE((TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage())); }

К

#define LOG_IF_FAILED(file_name, line, hr) if constexpr (FAILED(hr)) 
    { TRACE(TEXT("%s %i %s"), file_name, line, _com_error(hr).ErrorMessage()); }

То есть: от { TRACE((..., ..., ..., ...)); } до { TRACE(..., ..., ..., ...); }

Но я должен признать, что не знаю, есть ли какой-то другой непреднамеренный результат удаления лишних скобок.


1

Frodyne
3 Окт 2019 в 09:47

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

Читайте также:

  • Ошибка ce 37813 2 ps4
  • Ошибка client dll мта
  • Ошибка c6000 kyocera 2535dn
  • Ошибка ce 36329 3 на ps4 что это
  • Ошибка cl31 mta

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

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