Node:scanf, Next:String overflows with scanf, Previous:Deprecated formatted string input functions, Up:Deprecated formatted string input functions
scanf
The first of the functions we will examine is scanf
("scan
formatted"). The scanf
function is considered dangerous for a
number of reasons. First, if used improperly, it can cause your program
to crash by reading character strings that overflow the string variables
meant to contain them, just like gets
. (See gets.) Second,
scanf
can hang if it encounters unexpected non-numeric input
while reading a line from standard input. Finally, it is difficult to
recover from errors when the scanf
template string does not match
the input exactly.
If you are going to read input from the keyboard, it is far better to
read it with getline
and parse the resulting string with
sscanf
("string scan formatted") than to use scanf
directly. However, since sscanf
uses nearly the same syntax as
sscanf
, as does the related fscanf
, and since scanf
is a standard C function, it is important to learn about it.
If scanf
cannot match the template string to the input string, it
will return immediately -- and it will leave the first non-matching
character as the next character to read from the stream. This is called
a matching error, and is the main reason scanf
tends to
hang when reading input from the keyboard; a second call to scanf
will almost certainly choke, since the file position indicator of the
stream is not pointing where scanf
will expect it to. Normally,
scanf
returns the number of assignments made to the arguments it
was passed, so check the return value to see if scanf
found all
the items you expected.