Mail Archives: djgpp/1996/04/15/18:33:37
On Fri, 12 Apr 1996, Dale Robinson wrote:
> while(scanf("%d",&n) != EOF) {
> if (n < 0) {
> printf("warning: n is -ve\n");
> } else {
> printf("%d is correct\n", n);
> }
Never assume that `scanf' returns EOF when it hits an end of file. You
should in general test for the return value to be the expected number of
items you want to read (in this case 1), and if the returned value is
less than that, take an error action.
Btw, the current version of `scanf' has a bug that causes it to NEVER
return EOF, but even after that bug is corrected, relying on EOF is
unsafe. For instance if you try to read 2 items, like this:
scanf ("%d %d", &i, &j);
and press ^Z after typing only one number, ANSI C says that `scanf'
shouldn't return EOF, but 1. In general, it only has to return EOF when
it hits end of file ``before any conversion takes place''.
- Raw text -