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.
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.The
fgets()
function following the call toscanf()
is probably1 not getting skipped. It is probably1 returning immediately having found a newline in the input stream.Calling
scanf()
beforefgets()
almost always results inscanf()
leaving an unused newline ('\n'
) in the input stream, which is exactly whatfgets()
is looking out for.In order to mix
scanf()
andfgets()
, you need to remove the newline left behind by the call toscanf()
from the input stream.One solution for flushing stdin (including the newline) would be something along the lines of the following:
1 - It is difficult to be certain without seeing the actual code.
Or, as Jerry Coffin suggested in his comment below, you could use
scanf("%*[^\n]");
. The"%*[^\n]"
directive instructsscanf()
to match things that are not newlines and suppress assignment of the result of the conversion.From http://c-faq.com/stdio/gets_flush1.html:
Or, as Chris Dodd suggested in his comment below, you could use
scanf("%*[^\n]%*1[\n]");
. The"%*[^\n]%*1[\n]"
directive instructsscanf()
to match things that are not newlines and then match one newline and suppress assignment of the results of the conversion.