the purpose is to verify the user input, and sent error message if they enter integer when I asking for string, or enter string when I asking for integer, or any other weird symbol etc.
could anyone get me a full version of the example to demonstrate how to test for:
1.test for float type ( input ) 2.test for string type ( input ) 3.test for character type ( input )
and under below is my code for testing integer:
int getAge(){
int x;
puts("please enter your age:\n\n");
x = scanf("%d",&age);
if (x == 1){
printf("You have entered :%d",age);
return (age);
}
else {
wrongInput();
}
}
CodePudding user response:
num will always contain an integer because it's an int. The real problem with your code is that you don't check the scanf return value. scanf returns the number of successfully read items, so in this case it must return 1 for valid values. If not, an invalid integer value was entered and the num variable did probably not get changed (i.e. still has an arbitrary value because you didn't initialize it).
CodePudding user response:
An example for integers, with re-entering if not correct:
#include <stdio.h>
int main(void)
{
int age;
printf("Please enter your age: ");
while(scanf("%d", &age)!=1 || getchar()!='\n')
{
scanf("%*[^\n]%*c");
printf("You must enter your age: ");
}
printf("You have entered: %d\n", age);
return 0;
}
For floats or doubles the principle is the same.