Reputation: 564
there are many questions about flushing stdin, mine is not about how to flush it, rather about the meaning of the following function:
while((c = getchar()) != '\n' && c != EOF);
I am trying to think of scenarios why and how we would need EOF in this function for emptying stdin? The user types something and presses enter, and we empty the buffer until we find enter, where does EOF come in?
Thank you
Edit: Thank you very much for the first answer and the second comment, that answers my question and totally satisfies me.
Other than the scenario where we pipe our input from a file where we have a real EOF, which pretty much answered my question, I still do not understand why we would need EOF in any other scenario for a function like this. the user can only invoke EOF at the beginning of a line in the terminal, so it cannot be used for emptying the buffer.
Upvotes: 1
Views: 1122
Reputation: 727137
Your code does not "flush" stdin
. All it does is searching for the nearest '\n'
, or the end of the input, whichever comes first.
You can get an EOF
in several situations:
stdin
, meaning that the next attempt to read would return EOF
, ora.out <data.txt
The reasons why you may do it could be different, but most often it's clearing out the leftovers from some previous invalid input.
Upvotes: 4
Reputation: 181932
The statement you present reads the remainder of the current line from stdin
and discards it, whether the line ends with a newline character ('\n'
) or at the end of the stream (EOF
). As dasblinkenlight observes, that is not what is conventionally called a "flush".
getchar()
returns EOF
at the end of the stream or on error, and EOF != '\n'
, so without the the EOF
check, that statement would loop infinitely if it reaches the end of the stream.
It is by no means certain that the last line of the input will be newline-terminated. In fact, you could argue that the last line of a stream is the one terminated by the end of the stream, so the last line is never newline-terminated, though it may contain zero characters.
Upvotes: 1
Reputation: 126967
If the user inserts Ctrl-D (on Linux/OS X) or Ctrl-Z (on Windows), you get an EOF from stdin. Also, the standard input may be redirected from a file - in that case, at the end you get a "real" EOF.
In both these cases, without that check that loop would go on forever, waiting for a newline that will never come (insert melancholic music here).
Upvotes: 5