"broeisi" <br*******@gmail.com> writes:
What advantages does sscanf offer over scanf?
[snip]
By using fgets() and sscanf(), you divide the task into two parts:
getting the input line and extracting information from it.
scanf() consumes a variable number of characters from stdin, depending
on the format string and what's actually in the input line. It
commonly leaves a newline character on stdin, to be consumed by the
next input routine you call (which may not be able to handle it
properly). If you're trying to read, say, 3 input fields, and the
input only has 2 valid fields, scanf() will consume those two fields
and may leave you in the middle of the line.
In some cases, scanf() skips whitespace, *including* new-line
characters. If the user doesn't provide all the required fields on a
line, it keeps reading lines until you get all of them (or an error);
that's probably not what you want.
By contrast, fgets() consumes an entire line, including the trailing
newline. (That's not *quite* true; it only reads up to the maximum
number of characters you specify. You can either discard the rest of
the line after fgets(), or you can use a routine like the non-standard
but freely available ggets() that reads the entire line.) Once you
have the line in memory, you can use sscanf() to extract the required
information from it. sscanf(), like scanf(), returns the number of
items successfully translated. If that's less than the number you
asked for, you can reject the entire input line. If your program is
interactive, you can then prompt the user to try again.
--
Keith Thompson (The_Other_Keith)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.