how do I clear stdin buffer

der Mouse mouse at thunder.mcrcim.mcgill.edu
Tue Jun 18 15:56:03 AEST 1991


In article <43310 at cup.portal.com>, tms at cup.portal.com (Taos Mountain Software) writes:

> The stdio function "scanf" works great for input from datafiles, but
> I always run into problems when doing interactive tty I/O on Unix
> systems.

> For example, this simple program will go into an infinite loop if the
> entry is a non-digit for example ("abc").

[compressed, and unimportant stuff deleted -dM]
> 		do { stat=scanf("%d",&x); } while (stat != 1);

It will do the same thing when reading from a data file, too.  This is
not a bug; this is how scanf is supposed to work.

You generally don't want to use scanf for reading interactive input.
(You generally don't want to use it for reading files, either, except
for throwaway programs that you're certain will remain throwaway.)  You
probably should read a full line with fgets and then pick it apart with
sscanf, a character-based scanner, or something like my (unfortunately
not widespread) fopenstr....

> I know there are plenty of workarounds, but what I'm interested in is
> a function like fflush that deals with input streams.

What do you propose it do?  The best direct analogy to fflush that I
can think of is to have it read repeatedly until the stdio buffer is
filled (or EOF or an error occurs).  But since I can't see how that
would help you the slightest in this situation, you must want something
else.

					der Mouse

			old: mcgill-vision!mouse
			new: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list