c - Scanf 函数在查找 %d 匹配项时是否忽略 Enter 键?

标签 c whitespace scanf format-specifiers

我是 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:

  1. Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier. [....]

所以,是的,任何前导空格(存在于输入缓冲区中)都会跳过或被忽略% d.

关于c - Scanf 函数在查找 %d 匹配项时是否忽略 Enter 键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38039634/

相关文章:

c - c 中包含字符串的链接列表

php - 使用 HTML 生成一个打印机将忽略的空格

c - 如果语句不起作用?

c - 在 C 中没有附加参数的 scanf

c - 使用 sscanf 检查范围 '0 ' , '9' ,'.' .'+ and ' -' 符号之间的数字

c# - 将 C Union 转换为 C#(未正确对齐)

可以安全地读取 C 中未初始化的自动 volatile 变量吗?

html - 什么时候空格在 HTML 中很重要?

html - 有没有人知道在 html 中对齐脚本标签?因为我必须将脚本标签一个一个地对齐

c - 我的 c 数独生成代码有什么问题?