delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1998/11/09/03:25:58

Date: Mon, 9 Nov 1998 10:18:43 +0200 (IST)
From: Eli Zaretskii <eliz AT is DOT elta DOT co DOT il>
X-Sender: eliz AT is
To: Daniël Hörchner <dbjh AT usa DOT net>
cc: djgpp AT delorie DOT com
Subject: Re: scanf/gets bug?
In-Reply-To: <3645D45E.8A5C98E5@usa.net>
Message-ID: <Pine.SUN.3.91.981109101823.18112F-100000@is>
MIME-Version: 1.0
X-MIME-Autoconverted: from QUOTED-PRINTABLE to 8bit by delorie.com id DAA02169
Reply-To: djgpp AT delorie DOT com

On Sun, 8 Nov 1998, Daniël Hörchner wrote:

> I came across a weird problem with DJGPP (GCC 2.8.1). In the following
> program gets() should wait for input, but it doesn't. What's wrong?

`scanf' leaves the newline in the input buffer, and `gets' swallows
it.

> The
> strange thing is that if I insert a call to getch() between scanf() and
> gets(), getch() waits for input, but gets() still does not.

Not strange at all.  `getch' issues a low-level DOS call which
bypasses the buffering of stdio functions.  The newline that causes
`gets' to return immediately is in the buffer allocated by the stdin
stream, which `getch' doesn't check.

> With Turbo
> C++ 3.0 it works fine (i.e., gets() waits for input).

It works in Turbo C because this program uses a non-portable trick of
calling `fflush' on stdin, which doesn't do anything in most
implementations other than Borland's.

A *portable* way of making sure the newline is not left in the buffer
is to force `scanf' to consume it as well, like this:

      scanf ("%d\n", &x);

Since this is so simple, I am led to believe that whoever put that
`fflush' in the original program didn't quite know what was going on
there ;-).

- Raw text -


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