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=quit, n=new, l=list): " );
scanf( "%c", &command );
Flush();
}
while ( (command != 'q') && (command != 'n')
&& (command != 'l') );
printf( "\n----------\n" );
return( command );
}
void Flush( void ) {
while ( getchar() != '\n' )
;
}
What I don’t quite understand here is the usage of the Flush() function. I mean, the book I am reading explains it by saying that it prevents the user from inputting more than a single character and then having that character read when they are prompted for input the 2nd time.
What I don’t understand is how Flush() is preventing this from happening. It doesn’t DO anything. All it is is a while command. (While this is true……what?????) Doesn’t make sense.
getchar()has the side effect of removing the next character from the input buffer. The loop inFlushreads and discards characters until – and including – the newline\nending the line.Since the
scanfis 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
but it’s actually a generally bad example as it does not handle End Of File well.
In general
scanfis best forgotten;fgetsandsscanfwork much better as one is responsible for getting the input and the other for parsing it.scanf(andfscanf) try to do too many jobs at once.