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
CodePudding user response:
A simple method is to use fgets
after scanf
to clear stdin
.
#include <stdio.h>
int main(void) {
int T = 0, i = 0;
char S[10000];
printf("How many words? ");
scanf("%d", &T);
// Clear stdin with fgets so the "Type _ words" output displays before the first input prompt
fgets(S, sizeof(S), stdin);
while (i < T) {
// Decrement T instead of incrementing i as a performance optimization
printf("Type %d words ", T--);
fgets(S, sizeof(S), stdin);
printf("Your word: %s", S);
}
return 0;
}
Here's the result:
How many words? 2
Type 2 words a
Your word: a
Type 1 words b
Your word: b
I updated the answer below with output wording that makes more sense if others are reading this.
#include <stdio.h>
int main(void) {
int T = 0, i = 1;
char S[10000];
printf("How many words? ");
scanf("%d", &T);
// fgets() clears stdin so the "Type _ words" output displays before the first input prompt.
fgets(S, sizeof(S), stdin);
while (i < T) {
// T is decremented instead of incrementing i as a performance optimization
printf("Type a word [%d words remaining]: ", T--);
fgets(S, sizeof(S), stdin);
printf("Your word: %s", S);
}
printf("Type a word [1 word remaining]: ");
fgets(S, sizeof(S), stdin);
printf("Your word: %s", S);
return 0;
}
Here's the result.
How many words? 2
Type a word [2 words remaining]: a
Your word: a
Type a word [1 word remaining]: b
Your word: b