在查找 %d 匹配项时,Scanf 函数是否会忽略 Enter 键? [英] Does Scanf function ignore the Enter key when looking for %d match?

查看:71
本文介绍了在查找 %d 匹配项时,Scanf 函数是否会忽略 Enter 键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 语言的新手,我正在 Kim N. King 的书上学习它.它说 scanf() 寻找忽略空格的数字模式,但我认为它也会跳过 Enter 键.而如果它寻找字符,它显然也需要空格.

I'm new to to C language and I'm studying it on a book by Kim N. King. It say that the scanf() looks for number pattern ignoring the whitespaces but I think it also skips on Enter key. While if it looks for characters it obviously takes the whitespace also.

因此在这个示例代码中我必须使用 getchar() 在第二个 scanf() 之前清除流,否则第二个将在不等待的情况下执行用户的输入.

Therefore in this example code I have to use getchar() to clear the stream before the second scanf(), otherwise the second one would be executed without waiting for user's input.

printf("Enter a char: ");
scanf("%c", &ch1);
getchar();
printf("\nEnter another char: ");
scanf("%c", &ch2);

如果我改为查找数字,则没有问题.

If I look for digits instead, I have no problems.

printf("Enter a number: ");
scanf("%d", &n1);
printf("\nEnter another number: ");
scanf("%d", &n2);

我的假设(它跳过 Enter 键)对吗?

Is my assumption (It skips the Enter key) right?

推荐答案

ENTER 键输入一个 newline (\n),是一个空白字符.

Pressing ENTER key inputs a newline (\n), which is a whitespace character.

引用 C11,章节 §7.21.6.2,fscanf()

Quoting C11, chapter §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. 跳过输入的空白​​字符(由 isspace 函数指定),除非规范包括 [cn 说明符.[....]
  1. Input white-space characters (as specified by the isspace function) are skipped, unless the specification includes a [, c, or n specifier. [....]

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

So, yes, any leading whitespace (present in the input buffer) is (are) skipped or ignored for %d.

这篇关于在查找 %d 匹配项时,Scanf 函数是否会忽略 Enter 键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆