bug in scanf(3)

Alexis Dimitriadis alexis at reed.UUCP
Mon May 13 20:22:24 AEST 1985


Here is another problem I have noticed with scanf.  This one is really
a bug. (I think) :-)
  Consider the following program:
main()
{
	int a;

	while (scanf("%d\n", &a) > 0)
		printf("%d\n", a);
}
It prints each number after the NEXT one has been read.  If "%d" is used
to read in numbers, the problem disappears.

   This is because if blank, newline or tab is specified in the input
format, doscan() will read all the blanks in the input until it finds a
non-blank character.  (Sort of like the lookahead problem in Pascal,
only worse).

  I would be tempted to correct it by making it treat blanks in the
format like everything else, but since that was put in explicitly, it
may have a purpose. (At least an intended one).  The numerical input
routine does discard all leading white space, so that could not be
the reason.

  So if you know of the intended purpose, or why reading zero or one
blank when one is specified would not work, please let me know.
(The manual says that blanks, tabs and newlines match "optional" white
space in the input, hence the `zero or one').

  The offending code is on lines 82-83 of doscan.c, and reads as
follows:
      while ((ch1 = getc(iop))==' ' || ch1=='\t' || ch1=='\n')
		;

    Sincerely, 
    Alexis Dimitriadis
-- 
_______________________________________________
  As soon as I get a full time job, the opinions expressed above
will attach themselves to my employer, who will never be rid of
them again.

             alexis @ reed

	         ...teneron! \
...seismo!ihnp4! - tektronix! - reed.UUCP
     ...decvax! /



More information about the Comp.lang.c mailing list