Date: Mon, 9 Nov 1998 10:18:43 +0200 (IST) From: Eli Zaretskii X-Sender: eliz AT is To: Daniël Hörchner cc: djgpp AT delorie DOT com Subject: Re: scanf/gets bug? In-Reply-To: <3645D45E.8A5C98E5@usa.net> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII Content-Transfer-Encoding: 8bit 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 ;-).