www.delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1996/04/16/00:41:47

From: j DOT aldrich6 AT genie DOT com
Message-Id: <199604160421.AA018178512@relay1.geis.com>
Date: Tue, 16 Apr 96 04:10:00 UTC 0000
To: djgpp AT delorie DOT com
Mime-Version: 1.0
Subject: Re: End of file keyboard symbo

Reply to message 5423010    from AO950 AT FREENET on 04/14/96  4:24AM


>I've seen this sort of program. Usually it's just set to wait until a
>certain special number like 999 is entered that it treats as an exit command.
>Also done more elegantly as like this:
>
>Enter a number: 5
>5 is positive
>Do you wish to do another number? Y

I used to do something like that in my neophyte programming days.
Then I discovered gets().  Remember that if scanf() leaves everything
after the number it expects in the input buffer, which can wreak havoc
on further calls to ANY kind of input function unless the buffer is first
cleared by doing something like:

while ( getchar() != '\n' );

But even that could conceivably cause problems if the buffer was in
fact clear before it was done (the user would just see a pause until
he/she pressed Enter).

The idea solution to all of this is to simply use gets() and sscanf().
If gets() sees an EOF, it simply returns NULL, and no matter what
else goes on, it gets an entire input line, including the c/r.  So if
the user wants to end input with an EOF, just check the return value
of gets().

The other really nice thing about using gets() is that it doesn't force
the user to type anything before pressing Enter.  Just examine the
resulting buffer.  If you really expect input, just prompt the user again.

The moral is that scanf() is for beginning programmers.

John

- Raw text -


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