当我将 scanf 与 %d 或 %f 一起使用时,它会跳过空白字符。另一方面,当与 %c 一起使用时,它会读取空白字符。有人可以详细说明为什么会发生这种情况吗?
像下面的代码一样使用 %d 或 %f 会自动跳过空白字符
#include<stdio.h>
void main(void)
{
int i;
scanf("%d ",&i);
}
如果我像这样读取输入
#include<stdio.h>
void main(void)
{
char ch;
scanf(" %c ",&ch);
scanf(" %c",&ch); /*or like this*/
}
它会跳过空白字符。 为什么 scanf 使用格式说明符显示不同的行为???
最佳答案
基本上,这是因为空白字符对于 %d
或 %f
无效,因此它们会跳过它们。
但是空白字符是有效字符,因此 %c
将尝试处理它。
C99 §7.19.6.2 The fscanf function section 8
Input white-space characters (as specified by the
isspace
function) are skipped, unless the specification includes a[
,c
,orn
specifier.
关于c - 具有不同格式说明符的 scanf 函数的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18443577/