delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1994/09/01/12:12:01

To: ronis AT onsager DOT chem DOT mcgill DOT ca (David Ronis)
Cc: djgpp AT sun DOT soe DOT clarkson DOT edu
Subject: Re: bug in scanf()
Date: Thu, 01 Sep 94 16:52:53 +0200
From: eliz AT is DOT elta DOT co DOT il

> main()
> {
>	while(1)
>	{
>		int i,j;
>		j=scanf("%d",&i);
>		printf("i=%d; j=%d\n",i,j);
>	}
>}
>       However, if an invalid integer is entered, e.g., a character,
>scanf returns 0 and leaves i untouched (this is as expected).  The
>problem is that on the next loop scanf no longer reads the console.  It
>simply returns zero without reading any input.

This seems OK to me.  Once scanf() detects an invalid integer, it
can't possibly get past it (that's why it returns 0: to tell you
it have read *zero* fields) and thus doesn't move the stream
pointer.  The next time through the loop it tries to read that
same illegal field again, and again fails.... etc. ad infinitum.

The usual practice is to output an error message and bail out
if scanf() returns a number which is less than the number of
items it should have read.  If you want to resync (i.e. to
forget about the bad input) and allow the poor naive user to
correct his ways, just get past that line with gets(), or
get past the illegal input with scanf("%s", junk) where
junk[] is a character array.

	Eli Zaretskii

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019