Search code examples
cfgets

C first fgets() is being skipped while the second runs


The question is:

Why does the first fgets statement is being skipped? I read somewhere that it might be because of SCANF() that I used before. I am trying to figure it out but I can't. Can someone give me the solution (I should probably re-write the first bit of code to avoid scanf, but how?).

This in the code I am struggling with:

for(;;)
    {
            //Ask if the user wants to add another CD - Y/N
            fputs("\nWould you like to enter new CDs details?  y or n\n", stdout);
            scanf(" %c" ,&type);
            if (toupper(type) != 'Y')
                break;

            puts("");


            //getting in the album information        
            printf("\tLets enter the details of the CD %d:\n\n", count + 1);


            fputs("Title?\n", stdout);   

            //this fgets statement is being skipped
            fgets(title[count], sizeof title[count], stdin);
            title[count][strlen(title[count]) - 1] = '\0';

            fputs("Atrist? \n", stdout);
            fgets(artist[count], sizeof artist[count], stdin);
            artist[count][strlen(artist[count]) - 1] = '\0';
    }

Solution

  • This is because the last ENTER keypress, which causes a newline is left in the input buffer. This is picked up by the first fgets().

    You can add a while(getchar() != '\n'); before the first fegts() to avoid this.

    [EDIT: Or, for better, as mentioned by Chux Thanks to him in below comment,use something like

    int ch; while((ch = getchar()) != '\n' && ch != EOF);
    

    to handle the 'newline' as well as EOF.]

    That said, it is never a good choice to mix scanf() and fgets(). Use fgets() always, it is possible and better.