I'm trying to create a code in C that asks how many words the user wants to insert and then ask repeatidly for each of the words, but on the first iteraction of the loop the code skips the printf() statement and goes directly to the fgets() line, showing the printf() after. The real problem to me is why fgets() on line #10 is being executed before printf() on line #09 on the first iteraction of the loop (on subsequents iteractions they follow the proper order).
Here's my code:
#include <stdio.h>
int main(void) {
int T = 0, i = 1;
char S[10000];
printf("How many words? ");
scanf("%d ", &T);
while (i <= T){
printf("\nType %d words ", T-i+1);
fgets(S, sizeof(S), stdin);
printf("\n Your word: %s", S);
i++;
}
return 0;
}
The expected output is something like this:
How many words? 2
Type 2 words banana
Your word: banana
Type 1 words orange
Your word: orange
But what I get is something like this:
How many words? 2
banana
Type 2 words
Your word: banana
Type 1 words orange
Your word: orange