how to test input type in c programming

Viewed 55

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();
    }
}
3 Answers

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

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.

The question is too vague.

In C, a null terminated array of characters is called a "string". There is no prescription as to what characters are present, except that '\0' is considered to be the useful end of the string (in most cases, but not all.)

The string could be a series of digits ('0'-'9') that may be convertible into a number. Is a (single) leading '-' allowed to indicate negative numbers? Are spaces before and/or after the digit sequence allowed? Is e-notation allowed? (Where "13e3" means "13000"). Are "thousands separators" allowed? If a single '.' is typed at the end (that could be ignored), is the input invalid because it "looks like" it might be a floating point number? Where are range checks to be performed? (Not all numbers will fit into a 32/64bit integer value.) Is "a dozen" considered a number because it is commonly understood to mean 12?

The list goes on, and we thought 'integers' would be the easy one.

Not going to go on with this. The picture has been painted. Without even understanding the problem, it is pointless trying to write code that might be the solution.

Related