VS2015 scanf 函数报错 error C4996: 'scanf'

错误提示: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.

具体如下,这是一个计算输入字符串长度的程序:

#include "stdio.h"

int main() {
char s[30];
char* p;
scanf("%s", s);
p = s;
while (*p != ''){ p++; }
printf("%d ", p - s);
while (1);
return 0;
编译结果:
1>------ Build started: Project: Learnc, Configuration: Debug Win32 ------
1> inputandoutput.c
1>C:Program Files (x86)MSBuildMicrosoft.Cppv4.0V140Microsoft.CppCommon.targets(355,5): error MSB6006: "CL.exe" exited with code 2.
1>d:fivecppprojectlearnclearncinputandoutput.c(8): 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 declaration of 'scanf'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========


解释:VS认为c标准函数不安全,进行了一些处理。

要去除这个错误,有三个方法:

(1)根据提示

在文件顶部加入一行:#define _CRT_SECURE_NO_WARNINGS

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
int main() {
char s[30];
char* p;
scanf("%s", s);
p = s;
while (*p != ''){ p++; }
printf("%d ", p - s);
while(1);
return 0;
}
运行成功!
(2)根据提示:

在文件顶部加入一行:#pragma warning(disable:4996)


#pragma warning(disable:4996)
#include "stdio.h"

int main() {
char s[30];
char* p;
scanf("%s", s);
p = s;
while (*p != ''){ p++; }
printf("%d ", p - s);
while(1);
return 0;
}
运行成功!

(3)真正原因在与vs中的SDL检查。于是可以:右键单击工程文件-->属性(最后一个)-------->  c/c++  ------>SDL checks ------------> no.

改前:


改后:

然后运行成功!

tips:在新建项目时可以把SDL检查勾掉(默认是yes),就可以避免此问题!

原文:https://blog.csdn.net/jh0703/article/details/47820875 

原文地址:https://www.cnblogs.com/Ph-one/p/10582870.html