John said:
Neither option's that good, but of the two the first one is preferable.
You always want to test the value returned from getchar() for EOF,
rather than relying on feof() to tell you when you've hit the
end-of-file. feof() won't return true until *after* you've tried to
read beyond the end of the file, so you wind up looping once too often.
Both options given by rCs will loop the same number of times. In fact,
their behaviour is equivalent. When getchar() has returned EOF, then one
of feof(stdin) or ferror(stdin) must be true. The only cost is the time
spent making two additional function calls per loop, which is likely to
be negligible.
You could say that both of them loop once too often. That is on the
first time through the loop, when c is uninitialised.
I'd rewrite it as
while ((c = getchar() ) != EOF)
{
/* do something with c */
}
This is better merely because it avoids the first time through the loop
when c was uninitialised.
if (feof(stdin))
{
/* handle end-of-file condition */
}
else
{
/* handle error condition */
}
rCs's code would still have to perform this test or equivalent, after
the loop finished.