Whenever I do a scanf before a fgets the fgets instruction gets skipped. I have come accross this issue in C++ and I remember I had to had some instrcution that would clear the stdin buffer or something like that. I suppose there's an equivalent for C. What is it?
Thanks.
The call to `scanf` left a terminating character in the input string. This is a '\n' character that follows the number read for <year> variable. The first `fgets` call then gets this left over character instead of reading the input for variable <a>.
Why fgets doesn't work after scanf? This can be solved by introducing a “\n” in scanf() as in scanf(“%d\n”, &x) or by adding getchar() after scanf(). The fgets() function then read this newline character and terminated operation.
On the other hand, fgets() is a lot safer than gets() because it checks the bounds of maximum input characters.
fgets is likely going to be the better choice. You can then use sscanf() to evaluate it. For numeric types, scanf() does not need to do bounds checking. For string types, you can tell scanf() to do boundary checking.
I'll bet it's because of the \n stuck in the input stream.
See one of these questions:
I am not able to flush stdin.
How do I go about Flushing STDIN here?
scanf() causing infinite loop
or this answer.
Also: Why not to use scanf().
P.S. fgets()
is a function, not an instruction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With