4996 错误不再提示的方法

来源:互联网 发布:热聊营销软件 编辑:程序博客网 时间:2024/06/10 17:30

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

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

[cpp] view plain copy
print?
  1. #include "stdio.h"  
  2.   
  3. int main() {  
  4.     char s[30];  
  5.     char* p;  
  6.     scanf("%s", s);  
  7.     p = s;  
  8.     while (*p != '\0'){ p++; }  
  9.     printf("%d\n", p - s);  
  10.     while (1);  
  11.     return 0;  
编译结果:

[cpp] view plain copy
print?
  1. 1>------ Build started: Project: Learnc, Configuration: Debug Win32 ------  
  2. 1>  inputandoutput.c  
  3. 1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppCommon.targets(355,5): error MSB6006: "CL.exe" exited with code 2.  
  4. 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.  
  5. 1>  c:\program files (x86)\windows kits\10\include\10.0.10150.0\ucrt\stdio.h(1270): note: see declaration of 'scanf'  
  6. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========  



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


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

(1)根据提示

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


[cpp] view plain copy
print?
  1. #define _CRT_SECURE_NO_WARNINGS  
  2. #include "stdio.h"  
  3. int main() {  
  4.     char s[30];  
  5.     char* p;  
  6.     scanf("%s", s);  
  7.     p = s;  
  8.     while (*p != '\0'){ p++; }  
  9.     printf("%d\n", p - s);  
  10.     while(1);  
  11.     return 0;  
  12. }  
运行成功!

(2)根据提示:

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


[cpp] view plain copy
print?
  1. #pragma warning(disable:4996)  
  2. #include "stdio.h"  
  3.   
  4. int main() {  
  5.     char s[30];  
  6.     char* p;  
  7.     scanf("%s", s);  
  8.     p = s;  
  9.     while (*p != '\0'){ p++; }  
  10.     printf("%d\n", p - s);  
  11.     while(1);  
  12.     return 0;  
  13. }  
运行成功!


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

改前:

改前



改后:


改后





然后运行成功!

运行成功


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


新建时修改

0 0