Mail Archives: djgpp/1998/11/08/23:23:58
Danikl Hvrchner wrote:
>
> Hello fellow DJGPP-ers,
> 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? 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. With Turbo
> C++ 3.0 it works fine (i.e., gets() waits for input).
>
> Thanks in advance,
> Daniel
>
> #include <stdio.h>
>
> int main(void)
> {
> int x;
> char string[10];
>
> scanf("%d", &x);
>
> fflush(stdin);
> gets(string);
> puts("hello");
>
> return 0;
> }
The idea of `fflush' of an input stream clearing buffers is a Turbo C
extension; ANSI says the results of `fflush'ing an input stream are
undefined. It's intended to be used only for output.
`getch' does what you expect since it (if I recall correctly) reads
directly from the console instead of going through stdio streams.
This is one reason to avoid using `scanf' to read interactive streams.
It's often better to read the whole line with `fgets' and parse it with
`sscanf'. (`gets' is unsafe because you can never know that your buffer
is large enough.)
--
Nate Eldredge
nate AT cartsys DOT com
- Raw text -