Reputation: 420
When the user input is larger than the buffer size specified to fgets()
, the excess characters after then seem to be stored in the input buffer. When I call fgets()
again, it reads those excess characters from the input buffer as the user input. Example code:
int main()
{
char input[3];
int input_int;
while (1)
{
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
getchar();
input_int = atoi(input);
printf("Your input: %d\n", input_int);
if (input_int == 100)
{
break;
}
}
}
Example output (all in the same loop of the program):
Enter input: 12
Your input: 12
Enter input: 150
Your input: 15
Enter input: 32
Your input: 0
Enter input: 52
Your input: 2
Enter input: 8
Your input: 2
Enter input: 1
Your input: 0
How can I fix this behavior?
Upvotes: 0
Views: 482
Reputation: 1702
You should use a larger buffer, however you could consume the leftover characters using getchar()
if there is no '\n'
character in your buffer, fgets doesn't consume the newline character, instead it saves it if there is space available. Like so:
if (strchr(input,'\n') == NULL) /* no occurence of the newline character in the buffer */
{
while (getchar() != '\n')
;
}
Upvotes: 1