[comp.lang.c] Re^2: scanf

njk@freja.diku.dk (Niels J|rgen Kruse) (06/13/89)

scs@adam.pika.mit.edu (Steve Summit) writes:

>Scanf's most miserable problem is that it doesn't discard
>unrecognized input.  (This is a documented feature, so don't try
>getting it changed.  It is only a miserable problem when scanf
>is being used for interactive user input, which is what everybody
>uses it for.)  The 'a' sits there in the input buffer, causing
>each scanf to fail, and the correct digits you probably typed
>after the 'a' are never seen.

But if you want scanf to skip bad input, you can just tell it to do
so. In this case you could write
...
  scanf ("%*[^0123456789] %d",&d)
...
which will cause scanf to discard leading junk and then read
a number.
A skip-leading-junk conversion modifier would be nice though.
Perhaps a '!' could be used for that : scanf ("%!d",&d) .
-- 
         Niels J|rgen Kruse
Email    njk@diku.dk
Mail     Tustrupvej 7, 2 tv, 2720 Vanlose, Denmark

peter@ficc.uu.net (Peter da Silva) (06/13/89)

scs@adam.pika.mit.edu (Steve Summit) writes:
>It is only a miserable problem when scanf
>is being used for interactive user input, which is what everybody
>uses it for.

Anyone using scanf directly for interactive input... or for any input at
all... should have their head examined.

The only really safe way to use scanf() without freaking out the casual
user of your code is to do something like this:

	fgets(buffer, sizeof buffer, stdin);
	sscanf(buffer, fmt, args...);

Sure, you can probably cons up a format string that does what you want, but
who needs the aggravation?

[ By the way, it really bugs me that stdio is so inconsistant about the
  position of the inevitable 'stream' argument? In an ideal world that code
  would read "fgets(stdin, buffer, sizeof buffer)", no? ]

-- 
Peter da Silva, Xenix Support, Ferranti International Controls Corporation.

Business: uunet.uu.net!ficc!peter, peter@ficc.uu.net, +1 713 274 5180.
Personal: ...!texbell!sugar!peter, peter@sugar.hackercorp.com.