[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]
Re: Re: Re: Fw: Infinite Joy Ride(example)
On Tue, 10 Apr 2001, kamesh jayachandran wrote:
> It is the simple program that is given as an example to
> illustrate random file handling in "C For Linux Programming"
> The program works well if numeric values are given.If I
> give non numeric value say 'A'.It goes for infinite joy ride
From the C-FAQ http://www.faqs.org/faqs/C-faq/faq/
12.19: I figured I could use scanf() more safely if I checked its
return value to make sure that the user typed the numeric values
I expect, but sometimes it seems to go into an infinite loop.
A: When scanf() is attempting to convert numbers, any non-numeric
characters it encounters terminate the conversion *and are left
on the input stream*. Therefore, unless some other steps are
taken, unexpected non-numeric input "jams" scanf() again and
again: scanf() never gets past the bad character(s) to encounter
later, valid data. If the user types a character like `x' in
response to a numeric scanf format such as %d or %f, code that
simply re-prompts and retries the same scanf() call will
immediately reencounter the same `x'.
See also question 12.20.
References: ISO Sec. 126.96.36.199; H&S Sec. 15.8 pp. 357-64.
12.20: Why does everyone say not to use scanf()? What should I use
A: scanf() has a number of problems -- see questions 12.17, 12.18,
and 12.19. Also, its %s format has the same problem that gets()
has (see question 12.23) -- it's hard to guarantee that the
receiving buffer won't overflow.
More generally, scanf() is designed for relatively structured,
formatted input (its name is in fact derived from "scan
formatted"). If you pay attention, it will tell you whether it
succeeded or failed, but it can tell you only approximately
where it failed, and not at all how or why. It's nearly
impossible to do decent error recovery with scanf(); usually
it's far easier to read entire lines (with fgets() or the like),
then interpret them, either using sscanf() or some other
techniques. (Functions like strtol(), strtok(), and atoi() are
often useful; see also question 13.6.) If you do use any scanf
variant, be sure to check the return value to make sure that the
expected number of items were found. Also, if you use %s, be
sure to guard against buffer overflow.
References: K&R2 Sec. 7.4 p. 159.
#!!! If anything can go wrong, _FIX_ it. (To hell with MURPHY)
Ajay kumar Dwivedi