peace upon you all every one :
I’m having a little problem with the scanf() function
the following code asks three users about their age using
scanf("%i",&user_age)
and then it matches if user_age >= 18 and user_age <= 100 and scanf() returned something except zero.
if the user entered a character or any except integer scanf() fails and return zero then the code loop back and try to reread the user age .
the problem is that scanf() won’t re prompt the user to enter any thing !!
but just keep returning 0 and the program keep trying to reread the age
here is the code :
Code:
#include <stdio.h>
int main()
{
int i = 0;
int user_age = 0;
int scanf_result = 0;
for (i=1 ; i<=5 ; i++)
{
printf("user number %i Enter your Age : ",i);
scanf_result = scanf("%i",&user_age);
if (user_age >= 18 && user_age <= 100 && scanf_result > 0)
{
//if the user input is >= 18 and <= 100 and scanf() returned non zero (succeeded) then
//do some work with the user input
}
else
{
printf("your age should be an integer from 18 to 100 try again\n");
i = i -1;
}
}
printf ("\n");
return 0;
}