打印并扫描字符串 c

print and scan a string c

我想使用 Visual Studio 在 C 中扫描并打印一个字符串。

#include <stdio.h>

main() {
    char name[20];
    printf("Name: ");
    scanf_s("%s", name);
    printf("%s", name);
}

在我这样做之后,它没有打印名字。 可能是什么?

引用自the documentation of scanf_s,

Remarks:

[...]

Unlike scanf and wscanf, scanf_s and wscanf_s require the buffer size to be specified for all input parameters of type c, C, s, S, or string control sets that are enclosed in []. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.

所以,scanf_s

scanf_s("%s", &name);

是错误的,因为您没有传递表示缓冲区大小的第三个参数。此外,&name 求值为 char(*)[20] 类型的指针,这与 scanf_s 预期的 %s 不同(char*)。

通过使用第三个参数表示缓冲区的大小来解决问题,使用 sizeof_countof 并使用 name 而不是 &name:

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

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

name 是数组的名称,数组的名称“衰减”到指向其第一个元素的指针,该元素的类型为 char*,就像 %s scanf_s 预期。