[英]print and scan a string c
I wanted to scan and print a string in C using Visual Studio. 我想使用Visual Studio在C中扫描和打印字符串。
#include <stdio.h>
main() {
char name[20];
printf("Name: ");
scanf_s("%s", name);
printf("%s", name);
}
After I did this, it doesn't print the name. 在我这样做之后,它不打印名称。 What could it be? 会是什么呢?
Quoting from the documentation of scanf_s
, 引用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[]
. 与scanf
和wscanf
不同,scanf_s
和wscanf_s
要求为所有包含在[]
c
,C
,s
,S
或字符串控件集的输入参数指定缓冲区大小。 The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable. 字符的缓冲区大小作为附加参数传递,紧跟在指向缓冲区或变量的指针之后。
So, the scanf_s
所以, scanf_s
scanf_s("%s", &name);
is wrong because you did not pass a third argument denoting the size of the buffer. 是错误的,因为你没有传递表示缓冲区大小的第三个参数。 Also, &name
evaluates to a pointer of type char(*)[20]
which is different from what %s
in the scanf_s
expected( char*
). 此外, &name
计算为char(*)[20]
类型的指针,该指针与scanf_s
期望值( char*
)中的%s
不同。
Fix the problems by using a third argument denoting the size of the buffer using sizeof
or _countof
and using name
instead of &name
: 通过使用sizeof
或_countof
使用表示缓冲区大小的第三个参数并使用name
而不是&name
来修复问题:
scanf_s("%s", name, sizeof(name));
or 要么
scanf_s("%s", name, _countof(name));
name
is the name of an array and the name of an array "decays" to a pointer to its first element which is of type char*
, just what %s
in the scanf_s
expected. name
是数组的名称,数组的名称“衰减”到指向其第一个元素的指针,该元素的类型为char*
,只是scanf_s
预期的%s
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.