O
obdict
Hello,
I used scanf() in a while loop, which ensures that user input is
valid (must be an integer no greater than 21 or less than 3).
If user enters a number out of the range, or enters non-number,
he/she will be asked to retry.
/* start */
int n;
while(1){
printf("Please enter an integer (3 <= x <= 21): \n");
if(scanf("%d", &n) && (n >= 3) && (n <= 21)){
return n;
}
printf("The input must be a number within the (3, 21) range,
inclusive. Please retry.\n"); //Point A
}
/* End */
In the above code, the first condition (scanf("%d", &n))
tests whether user inputs a number. In my tests, since
the format specifier is %d, my take is that if user enters
anything other than an integer, scanf() will not modify n,
and will by itself return 0 indicating reading data has failed
as a result of type mismatch.
My problem is that when user inputs something other than
an integer, the scanf() never runs again, and this while loop
continues indefinitely.
Weirdly, if I input an integer out of the (3,21) boundary,
it runs correctly and re-prompts me for a new value.
Any opinion is welcome. Thanks in advance
I used scanf() in a while loop, which ensures that user input is
valid (must be an integer no greater than 21 or less than 3).
If user enters a number out of the range, or enters non-number,
he/she will be asked to retry.
/* start */
int n;
while(1){
printf("Please enter an integer (3 <= x <= 21): \n");
if(scanf("%d", &n) && (n >= 3) && (n <= 21)){
return n;
}
printf("The input must be a number within the (3, 21) range,
inclusive. Please retry.\n"); //Point A
}
/* End */
In the above code, the first condition (scanf("%d", &n))
tests whether user inputs a number. In my tests, since
the format specifier is %d, my take is that if user enters
anything other than an integer, scanf() will not modify n,
and will by itself return 0 indicating reading data has failed
as a result of type mismatch.
My problem is that when user inputs something other than
an integer, the scanf() never runs again, and this while loop
continues indefinitely.
Weirdly, if I input an integer out of the (3,21) boundary,
it runs correctly and re-prompts me for a new value.
Any opinion is welcome. Thanks in advance