www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2001/07/19/15:45:46

Date: Thu, 19 Jul 2001 15:45:02 -0400
Message-Id: <200107191945.PAA22471@envy.delorie.com>
X-Authentication-Warning: envy.delorie.com: dj set sender to dj AT envy DOT delorie DOT com using -f
From: DJ Delorie <dj AT delorie DOT com>
To: djgpp AT delorie DOT com
CC: mike AT hippies DOT fsnet DOT co DOT uk
In-reply-to: <9j7bsc$ilg$1@newsg4.svr.pol.co.uk> (mike@hippies.fsnet.co.uk)
Subject: Re: Problem with scanf
References: <9j7bsc$ilg$1 AT newsg4 DOT svr DOT pol DOT co DOT uk>
Reply-To: djgpp AT delorie DOT com
Errors-To: nobody AT delorie DOT com
X-Mailing-List: djgpp AT delorie DOT com
X-Unsubscribes-To: listserv AT delorie DOT com

>  fflush(stdin);

You can't flush an input stream.  That is only defined and supported
for output streams.  Even if DJGPP supported it, it wouldn't always do
what you expect - sometimes it would wipe out parts of the next line
or two in addition to the rest of the existing line.  Sometimes it
wouldn't wipe out the whole current line.

What you *should* do is use fgets() to read in the whole line, and
sscanf() to parse it.

You should also use %d to read integers.  I'm pretty sure %5[0-9]s is
not going to do what you want either - it wants five digits followed
by the letter s!  It's no different than using %5[0-9]hello.

You also need to flush stdout so your prompt appears.   Stdout
is line buffered.

int a;
char line[100];

printf ("Please input a number ");
fflush (stdout);
fgets (line, 100, stdin);
sscanf (line, "%d", &a);  /* could be a = atoi(line); */

- Raw text -


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