[SOLVED] how to test input type in c programming


This Content is from Stack Overflow. Question asked by yuchen liu

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:nn");
    x = scanf("%d",&age);
    if (x == 1){
        printf("You have entered :%d",age);
        return (age);
    else {


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).

This Question was asked in StackOverflow by yuchen liu and Answered by Star_Knight It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?