delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/2003/09/08/10:01:25

X-Authentication-Warning: delorie.com: mail set sender to djgpp-bounces using -f
From: LibraryUser <deliberately AT made DOT invalid>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: multiple fgets()
Date: Mon, 08 Sep 2003 09:04:49 -0400
Organization: Lincoln Memorial Library
Lines: 44
Message-ID: <3F5C7E71.DAE3BE36@made.invalid>
References: <3 DOT 0 DOT 1 DOT 16 DOT 20030907233739 DOT 385fbbf6 AT earthlink DOT net>
NNTP-Posting-Host: lincoln1.lincolnd.lib.me.us
Mime-Version: 1.0
X-Trace: murdoch.unet.maine.edu 1063026421 9708 169.244.27.75 (8 Sep 2003 13:07:01 GMT)
X-Complaints-To: news AT murdoch DOT unet DOT maine DOT edu
NNTP-Posting-Date: Mon, 8 Sep 2003 13:07:01 +0000 (UTC)
X-Mailer: Mozilla 4.7 [en]C-NSCPCD (Win98; U)
X-Accept-Language: en
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp
Reply-To: djgpp AT delorie DOT com

Ethan Rosenberg wrote:
> 
> Pardon me for askiing a question which might be trivial, but I am
> stumped.  I have a program with multiple fgets() in sequence; ie
> 
> fgets(mr, 9, stdin);
> .do something ....
> fgets(ga, 9, stdin);
> . do something ...
>         .
>         .
>         .
> If the user types more than 8 characters, the remaining characters
> are left in the keyboard(?) buffer, and are picked up by the next
> fgets.  How do I get rid of the remaining characters, before the
> following fgets.

First, check the return value of fgets against NULL.  If equal,
you have an i/o error or EOF.  Then check the last char of the
input string.  If it is '\n' you have a complete line, if not you
can flush the input line with something like:

   while ((EOF != (ch = getc(stdin)) && (ch != '\n'}) continue;

So the overall code will look something like:

   if (fgets(mr, 9, stdin)) {
      do something that doesn't alter mr;
      if ('\n' != mr[strlen(mr)-1)) {
         flushln(stdin);
      }
   }

where flushln calls the above suggested code embedded in a
function.  (ch must be an int).  It could also return "EOF == ch"
to enable the caller to detect EOF.

Another solution is to use ggets, which is freely available at:

  <http://cbfalconer.home.att.net/download/>

--
Replies should be to the newsgroup
Chuck Falconer, on vacation.

- Raw text -


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