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

本文详细介绍了在Visual Studio中使用scanf函数时遇到的安全警告问题,提供了三种解决方法,包括预处理器指令、pragma警告禁用和项目属性配置,帮助读者消除编译错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

改前:

 

 


改后:

 

 

 

 

 

 

然后运行成功!

 

 

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

 

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

 

转载于:https://www.cnblogs.com/Ph-one/p/10582870.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值