Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - While-Loop Duplicating Print Statements

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:

enter image description here

like image 817
CosmicBadger Avatar asked Mar 07 '26 03:03

CosmicBadger


1 Answers

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.

like image 92
haccks Avatar answered Mar 08 '26 21:03

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!