fgets doesn't work after scanf

scanf() reads exactly what you asked it to, leaving the following \n from the end of that line in the buffer where fgets() will read it. Either do something to consume the newline, or (my preferred solution) fgets() and then sscanf() from that string.


scanf leaves whitespace in the input buffer, including new-line characters. To use fgets to read the next line you need to manually remove the rest of the current line:

int c;
do{
    c = getchar();
}while(c != EOF && c != '\n');

This is a more Simpler solution

scanf("%d",&loops);
while ((getchar()) != '\n'); //This will consume the '\n' char
//now you're free to use fgets
fgets(string,sizeof(string),stdin);

Tags:

C

Scanf

Fgets