printf vs fprintf
Jesse Perry
jesse at proxftl.UUCP
Fri May 20 23:44:08 AEST 1988
In article <2454 at ritcsh.UUCP>, gregory at ritcsh.UUCP (Gregory Conway) writes:
>The
>point is really simple, don't use printf and scanf. Use, instead,
>fprintf (stdout, "....") and fscanf (stdin, "....", &whatever).
Please, PLEASE don't tell people to use either scanf() or fscanf().
Instead use gets() or fgets(), followed by sscanf(). Code which uses
scanf() or fscanf() is susceptible to a nasty problem if the input
stream is not correctly formatted. The problem is that these functions
do not stop reading input at end of line. They only stop when each %
item in the control string has been matched (or EOF is found). If the
user fails to enter all the fields expected by the control string, the
(f)scanf() function will assume that the missing data is on the
following line(s).
If this happens with scanf(), the program appears to hang -- it is
waiting for the user to enter that next line, but the user won't because
he is waiting for the results of the line he just entered (unaware that
the entered line is incomplete).
If the input stream for fscanf() is incorrect, the program will not
(typically) hang, but it will mung the input lines together in crazy
ways, and not report any error.
Using (f)gets() followed by sscanf() is much more reliable, since format
errors can be detected and reported immediately.
>Gregory Conway at Computer Science House UUCP: ...rochester!ritcv!ritcsh!gregory
>Rochester Institute of Technology, Rochester, NY
Jesse Perry (RIT '87 :-)
UUCP: uunet!proxftl!jesse
BITNET: allegra!novavax!proxftl at psuvax1.uucp
ARPA: sunvice!proxftl!jesse at sun.com
More information about the Comp.lang.c
mailing list