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

527 views Asked by At

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';
    }
3

There are 3 answers

2
Natasha Dutta On BEST ANSWER

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.

1
Spikatrix On

Simply change

scanf(" %c" ,&type);

to

scanf(" %c%*c" ,&type);

The reason that the first fgets gets skipped is that your scanf leaves a newline character in the stdin. fgets sees this character and consumes it, thus not waiting for furthur input.

The %*c tells scanf to read and discard a character.

0
unwind On

Yes, it's because your scanf() didn't read more than a single character, but the user pressed return. The return remains in the input buffer, so fgets() immediately sees that and returns.

Don't mix them, use only fgets().