Use the loop to clean up the rest of a line after an error
You use code similar to the loop in the question when you think there is debris left on a line of input after you (attempted to) read some data from standard input but the operation failed.
For example, if you have:
int n;
if (scanf("%d", &n) != 1)
…recover from error here?…
The error recovery should check for EOF (it is correct to use feof()
here — but see while (!feof(file))
is always wrong for how not to use feof()
), and if you didn't get EOF, then you probably got a letter or punctuation character instead of a digit, and the loop might be appropriate.
Note that you should always check that the scanf()
operations — or any other input operation — succeeded, and the correct check for the scanf()
family of functions is to ensure you got the expected number of successful conversions. It is not correct to check whether scanf()
returned EOF; you can can get 0 returned when there's a letter in the input queue and you ask for a number.
Beware EOF
Incidentally, the loop in the question is not safe. It should be:
int c;
while ((c = getchar()) != EOF && c != '\n')
;
If the loop in the question gets EOF, it continues to get EOF, and isn't going to do anything useful. Always remember to deal with it. Note the use of int c;
too — getchar()
returns an int
and not a char
, despite its name. It has to return an int
since it returns every valid character code and also returns a distinct value EOF, and you can't fit 257 values into an 8-bit quantity.