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. Показов 23114. Ответов 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 |
|
Модератор
12623 / 10122 / 6096 Регистрация: 18.12.2011 Сообщений: 27,154 |
|
|
01.07.2017, 17:41 |
5 |
|
#include <iostream> И что эта строка тут делает?
1 |
|
Catstail Модератор
33777 / 18814 / 3968 Регистрация: 12.02.2012 Сообщений: 31,558 Записей в блоге: 12 |
||||
|
01.07.2017, 18:09 |
6 |
|||
|
И что эта строка тут делает? — предлагаю ТС следующий код:
1 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
01.07.2017, 18:09 |
|
6 |
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
Выпускник МГУ им. М.В. Ломоносова
Solution to C4996: scanf and other errors in c language program (without scanf_s replacement)
- Problem instance
- Solution
- method 1
- Method 2
Under the VS compiler, c4996 warning or error feedback information may appear when debugging and compiling C language programs written in the VS compiler. Here are a few based on my own practical experience. Can solve such problems. The following is described by a specific example.
Problem instance
The following shows a simple code `:
int main()
{
int age = 0;
printf("Please enter your age:>");
scanf("%d",&age);
printf("The age you entered is: %dn",age);
return 0;
}
Error or warning prompt during debugging operation:
1>------ Build started: project: test, Configuration: Debug Win32 ------
1> test.c
1>h:2020c c++Learnclasscodetesttesttest.c(24): 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.
1> c:program files (x86)windows kits10include10.0.10150.0ucrtstdio.h(1270): note: See "scanf" statement
========== generate: Success 0 Failed 1 Newest 0 Skip 0 A ==========
The prompt said that replacing scanf with scanf_s can solve the problem, so according to the prompt, replace scanf in the code with scanf_s. The result after debugging is:
1>------ Build started: project: test, Configuration: Debug Win32 ------
1> test.c
1> test.vcxproj -> H:2020C C++LearnClassCodetestDebugtest.exe
========== generate: Success 1 Failed 0 Newest 0 Skip 0 A ==========
It can be seen that this method can indeed solve the problem.
However, in fact, scanf is a function provided by the C language to prevent the use of most compilers, and the scanf_s function is only a version provided by the VS compiler that it considers safe. It may not be applicable to other compilers and is not recommended.
Solution
method 1
Mentioned in the error message:
To disable deprecation, use _CRT_SECURE_NO_WARNINGS.
Therefore, add a line of code to the very beginning of the source program (before the header file):
#define _CRT_SECURE_NO_WARNINGS 1
After debugging and compiling, the problem is solved:
1>------ Build started: project: test, Configuration: Debug Win32 ------
1> test.c
1> test.vcxproj -> H:2020C C++LearnClassCodetestDebugtest.exe
========== generate: Success 1 Failed 0 Newest 0 Skip 0 A ==========
In order to avoid adding the above-mentioned line of code every time you write a program, the following provides a method to automatically generate the above-mentioned line of code from the source file generated by the creation and addition:
The path of visual studio installed by yourself———>Find Microsoft Visual Studio 14.0 and click——->Click VC——- —>Click vcprojectitems————>Right-click new++file.cpp and open it with Notepad++———>Add #define _CRT_SECURE_NO_WARNINGS 1 to the file and save . In the future, the newly created **.c file can only show the above code, which can solve the problem of scanf, strcpy, strcat and other functions warnings or errors in c4996.
Method 2
Similar to method 1, adding the following line of code before the header file can also solve the problem:
#pragma warning(distable:4996)
If you want the above line of code to appear automatically in the newly created .c file, please refer to the method procedure in Method 1.
- Remove From My Forums
-
Question
-
#include «stdafx.h»
void main()
{
int x,r;
x=0,r=0;
printf(«Please enter the first number : «);
scanf(«%d»,&r);
printf(«please enter the 2nd number : «);
scanf(«%d»,&x);printf(» after addition : %d n», r+x);
printf(» after subtraction : %d n», r-x);
int n;
n=r*x;
printf(» after multiplication : %d n», n);
n=r/x;
printf(» after division : %d n», n);}
error C4996: ‘scanf’: This function or variable may be unsafe. Consider using scanf_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS
Visual studio 2012 ultimate gives me this error ( currently using vs 12 on Windows 8 RC)
but Visual studio 2010 ultimate gives warning
COde doesnt compile
-
Edited by
Saturday, September 15, 2012 8:16 PM
-
Edited by
Answers
-
Visual Studio 2012 is stricter about deprecated functions than 2010 was.
Rather than just advising you that you need to do something about your use of
scanf, as Visual Studio 2010 did, it now FORCES you to do something about it.You need to switch to
scanf_sor use_CRT_SECURE_NO_WARNINGS.-
Proposed as answer by
Richie Hindle — Entrian Solutions
Saturday, September 15, 2012 8:17 PM -
Edited by
Richie Hindle — Entrian Solutions
Saturday, September 15, 2012 8:18 PM
Formatting -
Marked as answer by
Damon Zheng
Monday, September 24, 2012 9:08 AM
-
Proposed as answer by
