Mail Archives: djgpp/1998/11/09/03:25:58
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 -