[comp.std.c] Hints for using "scanf"

martin@mwtech.UUCP (Martin Weitzel) (01/17/90)

I've been following the discussion for some time and really enjoyed
it, but what should the 'poor' C-User conclude?

In the courses I teached about C before the advent of the ANSI
standard I often recommended *not* to use scanf() at all,
because its behaviour differs too much across different
implementations of the standard library.

It seems, that I do not have to change this advice, but only
the rationale: Do not use "scanf", because it's very unlikely,
that all the implementors of an ANSI C standard library
understand all the implications of a conforming "scanf". :-)

This advice does not apply to any input, that is the
unchanged output of some other program, which in principle
is under your control: In this case it is easy to avoid all
of the nasty problems, into which "scanf" might run.

If you want to analyze interactive (or unpredictable) input,
my advice is to read a complete line with "fgets" (avoid "gets"!!)
or read up to some other significant token with "gets/fgets".
After that, use "sscanf" on the buffer you just read.
With this procedure you have the advantage, that you allways
know, up to which point the input is read, and additionally
that you may try different format strings for the same part
of the input.

Furthermore, if you must do more complex analysis of input
sequences use 'lex' ... at least as prototyping tool.

-- 
Martin Weitzel, email: martin@mwtech.UUCP, voice: 49-(0)6151-6 56 83

gwyn@smoke.BRL.MIL (Doug Gwyn) (01/17/90)

In article <583@mwtech.UUCP> martin@mwtech.UUCP (Martin Weitzel) writes:
>If you want to analyze interactive (or unpredictable) input,
>my advice is to read a complete line with "fgets" (avoid "gets"!!)
>or read up to some other significant token with "gets/fgets".
>After that, use "sscanf" on the buffer you just read.

Yes, this is much cleaner than using fscanf().  You can also use
some of the str*() functions instead of or in addition to sscanf()
to parse the buffer.

Many X3J11 members disliked including *scanf() in the Standard, but
because it was widespread existing practice we had to do it.  Same
for gets().