scanf("%lf",&b);
fgets(str, 100, stdin);
In the above code, fgets
is not read until I add a space after %lf
(eg. scanf("%lf ",&b);
),
or press ctrl-d instead of enter in the terminal. Why is this so?
scanf("%lf",&b);
fgets(str, 100, stdin);
In the above code, fgets
is not read until I add a space after %lf
(eg. scanf("%lf ",&b);
),
or press ctrl-d instead of enter in the terminal. Why is this so?
Don't mix fgets()
and scanf()
.
scanf()
leaves a newline (when you press ENTER key) which terminates the input reading of fgets()
as fgets()
would as soon as it sees a newline character, effectively your fgets()
not reading anything at all.
fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.
When you have a whitespace in the format string (scanf("%lf ",&b);
), the scanf call would only return after you input a non-whitespace which will then be read by the fgets()
call. This approach is error-prone. Because you will be forced to input something if you don't read anything further.
Please see: Why does everyone say not to use scanf? What should I use instead?
The scanf("%lf",...)
will stop and wait for more input when it encounters whitespace in input. Adding a space to the format string causes the whitespace character (or characters) to be removed from stdin
, and the function to return.
Another way to cause scanf()
to return is to make it recognise an error of some form. One way is to make it seem like it has reached end of file. You haven't mentioned it, but your host system is some flavour of unix - typing CTRL-D (depending on terminal settings you may need to hit CTRL-D after a newline, or possibly enter it twice) makes it seem like end of file has been encountered. If you check the return value from scanf()
it will return EOF
in this case too. Different systems require different actions to trigger end of file though.
Either way, fgets(..., stdin)
cannot be called until scanf()
returns. Note that triggering end of file may (depending on terminal settings) also cause fgets(..., stdin)
to return EOF
(i.e. it won't necessarily read input).
It is a really bad idea to mix use of scanf()
(or related functions) and fgets()
on the same stream (stdin
in this case), because they do interact in strange ways (each relies on behaviour in interacting with the stream that the other doesn't provide)