- The computer must repeat the question till it recieves a valid response.
- It (output) goes like this indefinitely.
Reason :
- The problem is that you are receiving input only once in your code and then entering into loop to check for the
age
. -
since age value is not re-assigned after every iteration, if the first intput is
!=32767
it’s always wrong and enters into an infinite loop or also known as the odd loop.scanf("%d", &age); //scans only once do //enters loop { if (age == 32767) { printf("Error, retry: \n"); } else { printf("Cool."); } } while(age!=32767);
The if else statement is to catch the exception incase the user types something that is not an integer.
-
No,
if (age == 32767)
would only check if the entered response was equal to32767
or not. -
From @davmac ‘s comment , you can never check for an input value greater than the maximum value of the
int
variable. -
Instead it’d be better if you would assign a range this way
`if (age > 100 || age <0 )`
Solution :
to avoid this scan age
for every iteration and also see the changes I’ve done :
do{
printf("How old are you?\n");
if(scanf("%d", &age)==1) //checking if scanf is successful or not
{
if (age > 100 || age <0 )
{
printf("Error, retry: \n");
}
else
{
printf("Cool.");
break; //break loop when correct value is entered
}
}
else //if scanf is unsuccessful
{
char c;
printf("enter only integers\n");
do
{
scanf("%c",&c);
}while( c !='\n' && c!= EOF ); //consuming characters
}
}while(1); //always true
8
solved Repeating an Input till it is answered Correct