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';
}
This is because the last
ENTER
keypress, which causes anewline
is left in the input buffer. This is picked up by the firstfgets()
.You can add a
while(getchar() != '\n');
before the firstfegts()
to avoid this.[EDIT: Or, for better, as mentioned by Chux Thanks to him in below comment,use something like
to handle the 'newline' as well as
EOF
.]That said, it is never a good choice to mix
scanf()
andfgets()
. Usefgets()
always, it is possible and better.