When the while-loop runs after the first time, it prints my "Create new node" prompt twice before getting user input from stdin. Why is this? See linked image.
Code:
int main()
{
char userInput[2];
while(1)
{
printf("\nCreate new node? (y/n)\n");
printf(">>> ");
fgets(userInput, 2, stdin);
if(strcmp(userInput, "y") == 0)
{
printf("Yes\n");
}
else if(strcmp(userInput, "n") == 0)
{
printf("No\n");
exit(0);
}
}
}
Terminal Output:

fgets read string plus '\0' plus '\n'. Since userInput is of only 2 bytes, '\n' will not be read by fgets and will be there in the input buffer. On next iteration fgets will read '\n' left by the previous call of fgets.
Increase the buffer size and you will have no problem
char userInput[3];
or you can put
int ch;
while((ch = getchar()) != '\n' && ch != EOF);
just after fgets statement.
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