I am confused by a piece of code found in a function I am studying:
char GetCommand( void )
{
char command;
do {
printf( \"Enter command (q=
When you enter your character and press Enter, a newline character is generated by you pressing the Enter key and it remains in the buffer. This is problematic because it will wait around until the next time you require user input and it will be used for that input. Flush is used to flush the newline character from the input buffer so you don't have that problem. Flush actually uses the newline in the input buffer when it reads it and it is discarded, so it is no longer in the buffer.
getchar
reads one character from standard input. If you put it in a while
loop, it will continue to read one character at a time until the condition is false.
What the Flush
function is doing is reading until it encounters a newline (\n
). This is the character produced when the user hits the enter key.
So, the code you gave will read one character (I'm unclear on why it uses scanf
for this instead of simply getchar
, which would be faster), and then discards the rest of the input until the user hits enter.
If you were to feed this program foobar
, it would take the f
and discard the oobar
in the Flush
function. Without calling flush
, the f
could go to one scanf
, and the second scanf
would get the first o
.
getchar()
has the side effect of removing the next character from the input buffer. The loop in Flush
reads and discards characters until - and including - the newline \n
ending the line.
Since the scanf
is told to read one and only one character (%c
) this has the effect of ignoring everything else on that input line.
It would probably be more clear if the scanf was replace with
command = getchar();
but it's actually a generally bad example as it does not handle End Of File well.
In general scanf
is best forgotten; fgets
and sscanf
work much better as one is responsible for getting the input and the other for parsing it. scanf
(and fscanf
) try to do too many jobs at once.