Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets instructions gets skipped.Why?

Tags:

c

fgets

scanf

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.

like image 523
nunos Avatar asked May 25 '10 17:05

nunos


People also ask

Why is fgets getting skipped?

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 is not working?

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.

Why is fgets safer than gets?

On the other hand, fgets() is a lot safer than gets() because it checks the bounds of maximum input characters.

Is fgets safer than scanf?

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.


1 Answers

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.

like image 66
aib Avatar answered Oct 01 '22 06:10

aib