了解 "while (getchar() != '\n')"

Understanding "while (getchar() != '\n')"

我想更好地了解有关此命令的后台工作方式。

我开始尝试防止我的应用程序在 scanf() 收到 char 而不是它期望的 int 时失败。提供给我的解决方案是添加行 while (getchar() != '\n'); 以清除输入缓冲区。 它奏效了。太棒了!

但是因为我使用的是 scanf() 而不是 getchar() 我发现我使用完全不同的输入命令来清除缓冲区有点令人困惑。

我在谷歌上搜索了一下,据我所知,getchar() 使用了 stdin,这就是使用该命令清除的缓冲区。这也意味着 scanf() 在这种情况下也使用 stdin

这个假设正确吗?

I have been Googling it a bit and from what I can tell, 'getchar()' uses 'stdin' and that is the buffer that is being cleared with that command. That would by extension also mean that 'scanf' is also using 'stdin' in that case. Is that assumption correct?

是的,没错。

根据 documentation(强调我的):

[scnaf] Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.

是的,是这样的。它在文档中明确提到。

引用 C11 标准,章节 §7.21.6.2

The fscanf function reads input from the stream pointed to by stream, under control of the string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. [....]

和章节 §7.21.6.4

The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf.


只是想补充一点为什么你需要 getchar() 来清除 stdinscanf() 也从 stdin:

读取

scanf() 仅在匹配成功时从输入缓冲区中读取,由指定允许输入序列的格式指向。万一匹配失败,这是你的情况,提供 char 其中 int 是预期的(很可能,用户使用 %d 转换说明符),缓冲区中的输入保持未读状态并且有资格在下次调用 scanf() 时阅读。

因此,如果调用 scanf(),始终建议检查失败并使用 getchar() 清理缓冲区,逐个字符地读取 stdin 和return 字符读取为 unsigned char 在每次调用中强制转换为 int,从而消耗缓冲区中的 any 条目并将其清除。