This problem happens because the fgets
will read all the characters you ask for except one, because the last will always be a \0
, so if you asked him to collect only 10 characters but type:
Input:
abcdefghijklmno[enter]
It will pick up for your string only the abcdefghi\0
.
But the problem is with the rest of the input and the enter at the end of it, as it just got played on the keyboard buffer (stdin
) as a jklmno[enter]
then when the program finds the next data entry using the scanf
, this buffer will already be read instantly and already have a enter will already send this data to this input
But as already pointed out in the hkotsubo link in the comments, a very simple solution very commented to balance a problem generated by the overflow protection of fgets
, is to use the fflush(stdin);
to clean the keyboard buffer, which solves this problem in a simple way, however is not ideal and much less the insurance, so often you will see a larger solution to solve the problem more securely which is the:
int c;
while ( (c = getchar()) != '\n' && c != EOF ) { }
That one while
basically will consume your buffer until you find the enter and the End Of File.
Or even this solution that is not portable to other systems:
fseek(stdin, 0, SEEK_END);
They all work partially to mitigate keyboard input problems, if you want to see more to find a safer solution, also linked in the topic of the comment.
https://answall.com/a/111702/112052
– hkotsubo