为什么Visual Studio的scanf_s()函数不接受字符串输入?

bpzcxfmw  于 2022-12-02  发布在  其他
关注(0)|答案(1)|浏览(282)

我使用的是Visual Studio 2022,它将scanf()函数标记为不安全的,并建议使用scanf_s()。昨天我的老师教我们用C语言写字符串,给我们看了一个从键盘接收字符串的程序,我在编译器中试了一下。使用scanf_s()输入字符串返回了错误C4473C6064,尽管我的代码除了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无法接受字符串输入?

cngwdvgl

cngwdvgl1#

来自C标准 *K.3.5.3.2 fscanf_s函数)此说明与函数scanf_s的说明相同
4 fscanf_s函数等效于fscanf,只是c、s和[转换说明符应用于一对参数(除非用 * 表示隐藏赋值)。这些参数中的第一个与fscanf的相同。在参数列表中,该参数后面紧跟第二个参数,如果第一个参数指向一个标量对象,则它被认为是一个包含一个元素的数组。
所以你需要写

scanf_s( "%s", name, sizeof( name ) );

同样,scanf的调用

scanf("%s", name);

如果将其重写为

scanf( "%24s", name );

注意,根据C标准,不带参数的函数main应声明为

int main( void )

相关问题