I have created a small application to find max number by using user-defined function with parameter. When I run it, it shows this message
Error 1 error C4996: ‘scanf’: This function or variable may be unsafe.
Consider using scanf_s instead. To disable deprecation, use
_CRT_SECURE_NO_WARNINGS. See online help for details.
What do I do to resolve this?
This is my code
#include<stdio.h>
void findtwonumber(void);
void findthreenumber(void);
int main() {
int n;
printf("Fine Maximum of two numbern");
printf("Fine Maximum of three numbern");
printf("Choose one:");
scanf("%d", &n);
if (n == 1)
{
findtwonumber();
}
else if (n == 2)
{
findthreenumber();
}
return 0;
}
void findtwonumber(void)
{
int a, b, max;
printf("Enter a:");
scanf("%d", &a);
printf("Enter b:");
scanf("%d", &b);
if (a>b)
max = a;
else
max = b;
printf("The max is=%d", max);
}
void findthreenumber(void)
{
int a, b, c, max;
printf("Enter a:");
scanf("%d", &a);
printf("Enter b:");
scanf("%d", &b);
printf("Enter c:");
scanf("%d", &c);
if (a>b)
max = a;
else if (b>c)
max = b;
else if (c>a)
max = c;
printf("The max is=%d", max);
}
|
kaskaskas 0 / 0 / 0 Регистрация: 13.03.2016 Сообщений: 23 |
||||
|
1 |
||||
|
01.07.2017, 15:16. Показов 26596. Ответов 5 Метки нет (Все метки)
подскажите плиз в чем проблема?
1>—— Сборка начата: проект: project1, Конфигурация: Debug Win32 ——
0 |
|
Encephalopathy 70 / 70 / 55 Регистрация: 04.06.2016 Сообщений: 235 |
||||||||
|
01.07.2017, 15:25 |
2 |
|||||||
|
Зайди в файл stdafx.h в проекте,там после
добавь
0 |
|
0 / 0 / 0 Регистрация: 13.03.2016 Сообщений: 23 |
|
|
01.07.2017, 17:09 [ТС] |
3 |
|
а если нет этого файла?
0 |
|
Encephalopathy 70 / 70 / 55 Регистрация: 04.06.2016 Сообщений: 235 |
||||
|
01.07.2017, 17:37 |
4 |
|||
|
тогда в начале файла вышей программы введи
Добавлено через 2 минуты
1 |
|
Модератор 13245 / 10387 / 6210 Регистрация: 18.12.2011 Сообщений: 27,784 |
|
|
01.07.2017, 17:41 |
5 |
|
#include <iostream> И что эта строка тут делает?
1 |
|
Catstail Модератор 35598 / 19496 / 4074 Регистрация: 12.02.2012 Сообщений: 32,533 Записей в блоге: 13 |
||||
|
01.07.2017, 18:09 |
6 |
|||
|
И что эта строка тут делает? — предлагаю ТС следующий код:
1 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
01.07.2017, 18:09 |
|
6 |
При использовании scanf выдаёт ошибку:
char str;
printf("qwe");
scanf("%s", &str);
return 0;
Ошибка 2 error C4996: 'scanf': This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. e:decanatconsoleapplication15consoleapplication15consoleapplication15.cpp 11 1 ConsoleApplication15
После добавления#define _CRT_SECURE_NO_WARNINGS
ничего не меняется.
А при использовании scanf_s, программа запускается но после ввода значения выкидывает такую ошибку:
2 Августа 2017
Время чтения: 5 минут
Компилятор в Visual Studio сильно отличается от привычных большинству программистов GCC или CLANG, из-за чего при написании кода на C или C++ очень часто возникают неожиданные проблемы в виде ошибки использования стандартных функций, например, scanf, fopen, sscanf и тому подобным. Студия предлагает заменять функции на безопасные (повезёт, если нужно просто добавить _s к функции с ошибкой, но нередко в этих функциях идёт иной набор аргументов, нежели в обычной программе). Если вы не готовы с этим мириться, то этот пост для вас!
Давайте для начала создадим обычный консольный проект в Visual Studio и напишем простенькую программу, которая запрашивает ввод двух чисел, вводит их и затем выводит на экран.
#include "stdafx.h"
#include <stdio.h>
int main() {
int a, b;
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%d", &b);
printf("a: %d, b: %dn", a, b);
return 0;
}
Попробовав выполнить сборку проекта, обнаружим те самые ошибки.
Чтобы Visual Studio не тратила ваши нервы, сделаем следующее:
1. Выберем пункт «Проект» в верхнем меню
2. В открывшемся списке щёлкнем по «Свойства название_проекта»

Программа, вводящая два числа и выводящая их

Ошибка компиляции из-за небезопасности функций

Проект — Свойства {навание проекта}
3. В появившемся окне выберем Свойства конфигурации, C/C++, Препроцессор
4. В строке Определения препроцессора допишем в самый конец строку ;_CRT_SECURE_NO_WARNINGS
5. Нажмём ОК

Свойства конфигурации

Определения препроцессора

Нажимаем OK
6. Попробуем заново выполнить сборку проекта:

Успешная сборка проекта
Ошибки исчезли, сборка прошла успешно и программа прекрасно работает! Теперь можно писать код как обычно, не переживая о необычном поведении Visual Studio!

Программист, сооснователь programforyou.ru, в постоянном поиске новых задач и алгоритмов
Языки программирования: Python, C, C++, Pascal, C#, Javascript
Выпускник МГУ им. М.В. Ломоносова
Compile the C language project in VS, if the scanf function is used, the following error will be prompted when compiling:
error C4996:’scanf’: This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
The reason is that Visual C++ uses more secure run-time library routines. The new Security CRT functions (that is, those with the “_s” suffix), please see
“Security Enhanced Version of CRT Function”
The solution to this problem is given below:
Method 1 : Replace the original old functions with new Security CRT functions.
Method 2 : Use the following methods to block this warning:
- Define the following macros in the precompiled header file stdafx.h (note: it must be before including any header files):
#define _CRT_SECURE_NO_DEPRECATE
- Or statement
#pragma warning(disable:4996)
- Change the preprocessing definition:
Project -> Properties -> Configuration Properties -> C/C++ -> Preprocessor -> Preprocessor Definition, add:
_CRT_SECURE_NO_DEPRECATE
Method three : Method two does not use the more secure CRT function, which is obviously not a good method worth recommending, but we don’t want to change the function names one by one. Here is an easier method:
Define the following macros in the precompiled header file stdafx.h (also before including any header files):
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
When linking, it will automatically replace the old functions with Security CRT functions.
Note: Although this method uses a new function, it cannot eliminate the warning. You have to use method two (-_-) at the same time. In other words, the following two sentences should actually be added to the precompiled header file stdafx.h:
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
Explanation of the cause of the error:
This kind of warning from Microsoft is mainly because of the functions of the C library. Many functions do not perform parameter detection (including out-of-bounds). Microsoft is worried that using these will cause memory exceptions, so it rewrites the functions of the same function. The function of has carried out parameter detection, and it is safer and more convenient to use these new functions. You don’t need to memorize these rewritten functions specifically, because the compiler will tell you the corresponding safe function when it gives a warning for each function. You can get it by checking the warning message. You can also check MSDN for details when you use it.

