为什么我不能使用“scanf_s"同时读取一个字符和一个数字? [英] Why can't I use 'scanf_s' for reading a character and a number at once?
问题描述
此代码崩溃:
scanf_s("%c %d",&ch,&x);//Run error
但此代码有效:
scanf_s("%c",&ch);
scanf_s("%d",&x);//Run succeed
我想知道为什么第一个代码片段是错误的.
I want to know why the first code fragment is wrong.
'运行错误'是指当我运行程序输入时,编译器有警告和错误
'run error' means The compiler has a warning and something is wrong when I run the program input
推荐答案
当您使用 scanf_s
(相对于 scanf
)时,您需要提供额外的长度%c
的参数(例如,参见 this 来自微软的关于 scanf_s
的文档:
As you are using scanf_s
(in contrast to scanf
), you need to provide an additional length parameter for %c
(cf, for example, this document from microsoft regarding scanf_s
):
与 scanf 和 wscanf 不同,scanf_s 和 wscanf_s 需要您指定某些参数的缓冲区大小.指定所有 c、C、s 的大小,S,或字符串控制集[]参数.
Unlike scanf and wscanf, scanf_s and wscanf_s require you to specify buffer sizes for some parameters. Specify the sizes for all c, C, s, S, or string control set [] parameters.
所以你必须写
scanf_s ("%c %d", &ch, 1, &x);
表示第一个 %c
最多读取一个字符.
indicating that the first %c
shall read at most one character.
请注意,scanf_s("%c",&ch);
也应该发出相同的警告/错误,因为它也缺少 %c
的强制性长度参数.
Note that scanf_s("%c",&ch);
should issue the same warning/error as it lacks the mandatory length parameter for %c
, too.
Command scanf_s("%d",&x);
相反,可以,因为 %d
不需要(不得提供)额外的长度参数.
Command scanf_s("%d",&x);
, in contrast, is OK as %d
does not require (must not get provided) an additional length parameter.
这篇关于为什么我不能使用“scanf_s"同时读取一个字符和一个数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!