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 != '\0'){ p++; }
	printf("%d\n", p - s);
	while (1);
	return 0;
编译结果:

1>------ Build started: Project: Learnc, Configuration: Debug Win32 ------
1>  inputandoutput.c
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(355,5): error MSB6006: "CL.exe" exited with code 2.
1>d:\five\cppproject\learnc\learnc\inputandoutput.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 kits\10\include\10.0.10150.0\ucrt\stdio.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 != '\0'){ p++; }
	printf("%d\n", 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 != '\0'){ p++; }
	printf("%d\n", p - s);
	while(1);
	return 0;
}
运行成功!


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

改前:

VS2015 scanf 函数报错 error C4996: 'scanf'_第1张图片



改后:


VS2015 scanf 函数报错 error C4996: 'scanf'_第2张图片





然后运行成功!

VS2015 scanf 函数报错 error C4996: 'scanf'_第3张图片


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


VS2015 scanf 函数报错 error C4996: 'scanf'_第4张图片


下面是一些参考:

(1)http://bbs.csdn.net/topics/390508208

(2)stackoverflow


你可能感兴趣的:(C语言,c语言,C,C4996,scanf,VS15)