使用Getchar时清除缓冲区(必须有更好的方法!) [英] Clearing the buffer when using Getchar (there must be a better way!)

查看:991
本文介绍了使用Getchar时清除缓冲区(必须有更好的方法!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个只需要获取一个数字的函数,所以我决定使用getchar()而不是scanf().

I am writing a function where I only need to obtain a single digit, I decided to use getchar() instead of scanf().

但是,由于我只需要一个字符,所以我没有使用数组来获取它.这引起了一个问题,因为我没有循环来查找'/n'字符.为了确保在再次使用getchar()之前清除缓冲区,我写了这样的话:

However since I only need one character I did not use an array to obtain it. This causes a problem because I dont have a loop to find the '/n' character. To make sure my buffer is cleared before using getchar() again, I wrote this:

while (getchar() != '\n'){}

它可以按我的需要工作,但这是解决此问题的正确"方法吗?

It works as I need it to, but is this the "correct" way to go about this problem?

我尝试使用fflush(stdin),但似乎没有任何作用.

I tried using fflush(stdin), but it seems to not have any effect.

感谢您的所有答复,我会经常检查评论,并很乐意回答问题.

Thank you for all replies, I check the comments often and would love to answer questions.

推荐答案

请注意,尽管一些实现支持fflush(stdin),但根据C标准,它是未定义的行为.

Note that fflush(stdin) is undefined behavior according to the C Standard, though it is supported by a few implementations.

惯用的方法是:

int c;
while ((c = getchar()) != '\n' && c != EOF) {
    continue;
}

需要检查EOF,以避免在getchar()中出现错误或用户从键盘上发出EOF信号时发生无限循环.变量c必须为int,以确保它可以容纳EOF的值,该值通常为-1.

The check for EOF is needed to avoid an infinite loop in the event that there is an error in getchar(), or if the user signals EOF from the keyboard. The variable c needs to be an int to ensure that it can hold the value of EOF, which is typically -1.

还请注意,此方法要求输入流中至少剩余一个字符,否则getchar()将阻塞,等待输入.先前对getchar()scanf()的调用将至少留下一个换行符,但对fgets()的调用则可能不会.

Also be aware that this method requires that there be at least one character left in the input stream, otherwise getchar() will block, waiting for input. A previous call to getchar() or scanf() will leave at least a newline behind, but calls to fgets() may not.

这篇关于使用Getchar时清除缓冲区(必须有更好的方法!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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