Wrong data type

How would I check for proper data type when someone is to input a value into the program? Ex:
1
2
3
4
5
6
7
int i;
string a;

cout << "Enter a number: ";
cin >> i;
cout >> "Enter a string: ";
cin >> a; 


How would you check to make sure that int i would be an actual number and not a letter like "a"?
C++ is a statically typed language, that means you can not check for data type.

You could accept a string whilst asking for a number, and then parse it starting from the first element in the string, into a number.

see std::atoi and std::strtol for more info.
If you mean how to check if input is number or string you could use the isdigit() function
I didn't even know about that Dk786.

Usually I create such function myself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

bool isInt(std::string &ref)
{
    switch (ref[0])
    {
        case '.':
        case '0':
        case '1':
        case '2':
        case '3':
        case '4':
        case '5':
        case '6':
        case '7':
        case '8':
        case '9':
            return true;
        default:
            return false;
    }
}


Cool that the standard lib has such functions...
1
2
3
4
5
6
7
8
9
template <typename T>
inline void validated_input(T& value)
{
    while( !(std::cin >> value) ) {
        std::cout << "Wrong input, try again: ";
        std::cin.clear();
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
    }
}

Usage: int x; validated_input(x); or int x; validated_input<int>(x);
Last edited on
Topic archived. No new replies allowed.