The scanf
family of functions, while quite powerful, is most often
used only by beginners (because they do not know other ways of input)
or for simple conversions from string to other types (where the strtoX()
family of functions is much more appropriate).
Problems of scanf
and fscanf
, regarding keeping track of
position...
scanf
and fscanf
,
we only use sscanf
in the following
examples. You should do the same in your code.
One of the most common problem beginners have with scanf
is the need
to provide pointers to the variables that ultimately shall hold the parsed values.
Since scanf
is a function that takes a variable number of arguments,
they are not type-checked as usual. Because of this, you can provide non-pointer arguments,
pointers to the wrong type,
or pointers to strings instead of just strings, and the compiler will not fetch these
errors at compile time. If you are lucky, you get a segment violation at run-time;
if not, you'll get other behaviour.
!!! \% vs. %% !!!
The following code shows those common errors and the correct code on consecutive lines:
Another common error is not to check the return type of scanf
,
which you always should do. scanf
returns the number of
sucessfully scanned fields, so a proper scanf
calls looks like this:
Brian W. Kernighan, Dennis M. Ritchie,
The C Programming Language.
Prentice Hall, 1988, 2nd edition, ISBN 0-13-110362-8.