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:
The check for
EOF
is needed to avoid an infinite loop in the event that there is an error ingetchar()
, or if the user signalsEOF
from the keyboard. The variablec
needs to be anint
to ensure that it can hold the value ofEOF
, 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 togetchar()
orscanf()
will leave at least a newline behind, but calls tofgets()
may not.