jay said:
Why this advice ? I think C-FAQs tell about enough of the issues
related with scanf.
It's good to know the issues, but if the advice it simply not to use
scanf, ever, then I disagree. If you are using C for some simple
numerical task, I think scanf is fine. You'll see I went on the explain
the main reasons to avoid it -- when you worry about overflow and where
line endings are significant.
http://c-faq.com/stdio/scanfprobs.html
footnotes explanation by "your truly" give much better case against
scanf.
No, it explains the problems that you might encounter mixing scanf and
gets (yes, gets!). It is not about using scanf on its own. In
particular, the summery says:
"The 'better way', as indicated in the FAQ list, is either to abandon
scanf entirely, or to use it exclusively."
Not much of a case against scanf. [By the way, it describes using gets
with a dummy buffer to read an discard up to the end of a line as "ugly,
unclean" and "unsatisfying". It omits to say "horribly unsafe". The
page dates, I think, from a more innocent era.]
strtol() is what I always use myself.
You are careful about input. That's good. If, on day one of Numerical
Analysis 101, you were asked to write something like this:
int main(void)
{
int n = 0;
double sum = 0, sum_sq = 0, x;
while (scanf("%lf", &x) == 1) {
n += 1;
sum += x;
sum_sq += x*x;
}
if (n)
printf("N=%d, mean=%g, var=%g\n",
n, sum/n, (n*sum_sq - sum*sum)/(n*n));
}
How would you do it, and would it be worth the effort?
I think OP used it in correct way:
Note that I did not say it was incorrect, but presumably you are saying
that I was wrong to say that it includes a redundant test.
Section 15.6, H&s5, (regarding getchar())
"If an error occurs or if the stream is at end of file, then fgetc
returns EOF. The feof and/or ferror facilities should be used in this
case to determine whether end of file has really been reached."
Section 15.1, H&S5 (regarding EOF):
"Because EOF is sometimes used to signal other problems, it is best to
use feof() facility to determine whether end of file has indeed been
encountered when EOF is returned."
I don't see anything there that contradicts what I said. Why do you
think it does?