我使用的是Visual Studio 2022,它将scanf()
函数标记为不安全的,并建议使用scanf_s()
。昨天我的老师教我们用C语言写字符串,给我们看了一个从键盘接收字符串的程序,我在编译器中试了一下。使用scanf_s()
输入字符串返回了错误C4473
或C6064
,尽管我的代码除了scanf()
不同之外,与我老师的完全相同。
#include<stdio.h>
#include<stdlib.h>
void main() {
char name[25];
printf("Enter your name ");
scanf_s("%s", name);//gave an ERROR
printf("Hello %s!", name);
}
我尝试使用常规的scanf()
沿着禁用警告,它工作了。
#include<stdio.h>
#include<stdlib.h>
#pragma warning(disable : 4996)
void main() {
char name[25];
printf("Enter your name ");
scanf("%s", name);//worked as intended
printf("Hello %s!", name);
}
为什么scanf_s
无法接受字符串输入?
1条答案
按热度按时间cngwdvgl1#
来自C标准 *K.3.5.3.2 fscanf_s函数)此说明与函数
scanf_s
的说明相同4 fscanf_s函数等效于fscanf,只是c、s和[转换说明符应用于一对参数(除非用 * 表示隐藏赋值)。这些参数中的第一个与fscanf的相同。在参数列表中,该参数后面紧跟第二个参数,如果第一个参数指向一个标量对象,则它被认为是一个包含一个元素的数组。
所以你需要写
同样,
scanf
的调用如果将其重写为
注意,根据C标准,不带参数的函数main应声明为