我想使用 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
andwscanf
,scanf_s
andwscanf_s
require the buffer size to be specified for all input parameters of typec
,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]
类型的指针这与 %s
不同在scanf_s
预期( char*
)。
通过使用表示缓冲区大小的第三个参数来解决问题 sizeof
或 _countof
并使用 name
而不是 &name
:
scanf_s("%s", name, sizeof(name));
或
scanf_s("%s", name, _countof(name));
name
是数组的名称,数组的名称“衰减”到指向其第一个元素的指针,该元素的类型为 char*
,到底是什么 %s
在scanf_s
预期。
关于c - 打印并扫描字符串 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29629531/