while((c = getchar()) != '\n' && c != EOF);
This reads input characters until it reaches either the end of the line (i.e., getchar()
returned '\n
) or end-of-file or an error condition (i.e., getchar()
returned EOF
).
If stdin
is reading from the keyboard, it discards input until you press Enter.
Leaving off the EOF
check could give you an infinite loop if there's an input error, or if you trigger an end-of-file condition (on Unix, by typing Ctrl-D twice).
This could be useful, for example, after using scanf()
to read an integer. If you execute scanf("%d", &num);
and type 123
, it will read those 3 digits (and store the value 123
in n
), but leave everything after that waiting to be read. The above line can be used to skip the rest of the input line.
(An alternative, likely a better one, is to read whole lines using fgets()
and parse them using sscanf()
.)
This is not equivalent to fflush(stdin)
. A far as the C standard is concerned, calling fflush
on an input stream has undefined behavior.
Some implementations do define the behavior of fflush(stdin)
. On systems that use GNU libc, for example (most Linux system):
For input streams, fflush()
discards any buffered data that has
been fetched from the underlying file, but has not been consumed by
the application.
That's not the same as discarding input up to the end of the line. And using it makes your code non-portable.