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.
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