Clearing the buffer when using Getchar (there must be a better way!)

梦想的初衷 提交于 2019-12-04 02:18:07

问题


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

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?

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.


回答1:


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

The idiomatic way to do this is:

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

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.

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.



来源:https://stackoverflow.com/questions/43954160/clearing-the-buffer-when-using-getchar-there-must-be-a-better-way

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!