Reputation: 3
So I'm trying to keep asking the user for a number until a number is entered and then print the result but I can't get scanf to be called after the first iteration. Any help would be appreciated.
int main(void) {
int x;
int entered_an_number = 0;
while(!(entered_an_number)) {
printf("Please enter a number: \n");
if(scanf("%d", &x) == 1) {
entered_an_number = 1;
}
}
printf("You entered: %d \n", x);
return 0;
}
Upvotes: 0
Views: 140
Reputation: 224854
The short answer, like the answer to most scanf
questions, is don't use scanf
. Use fgets
to read a line of input and then scan inside that input, e.g.:
char input[128];
fgets(input, sizeof input, stdin);
if(sscanf(input, "%d", &x) == 1) {
entered_an_number = 1;
}
Upvotes: 3