我是 C 语言新手,正在阅读 Kim N. King 的书来学习它。它说 scanf()
查找忽略空格的数字模式,但我认为它也会跳过 Enter 键。如果它查找字符,它显然也会查找空格。
因此,在这个示例代码中,我必须在第二个 scanf()
之前使用 getchar()
清除流,否则第二个将被执行而无需等待用户的输入。
printf("Enter a char: ");
scanf("%c", &ch1);
getchar();
printf("\nEnter another char: ");
scanf("%c", &ch2);
如果我寻找数字,则没有问题。
printf("Enter a number: ");
scanf("%d", &n1);
printf("\nEnter another number: ");
scanf("%d", &n2);
我的假设(它跳过 Enter 键)对吗?
最佳答案
按 ENTER 键输入一个换行符
(\n
),它是一个空白字符。
引用 C11
,第 §7.21.6.2 章,fscanf()
A directive that is a conversion specification defines a set of matching input sequences, as described below for each specifier. A conversion specification is executed in the following steps:
- Input white-space characters (as specified by the
isspace
function) are skipped, unless the specification includes a[
,c
, orn
specifier. [....]
所以,是的,任何前导空格(存在于输入缓冲区中)都会跳过或被忽略% d
.
关于c - Scanf 函数在查找 %d 匹配项时是否忽略 Enter 键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039634/