How to check if cin is int or string?

How do you check if the user input is actually a string or an integer?

i looked it up on the internetz and there were a number of different ways, but it doesn't seem to work, i think i need to check if something is actually a number.

Here's the hodgepodge that i put together from what people said, it obviously doesn't work.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
	while(valid==true)
		{
		cin >> choice1;
		if (!cin) 
		{
		cout << "Enter a valid name fool.\n" << "Try again:  " << endl;
		cin.clear();
		cin.ignore(100, '\n');
		continue;
		}
		else
			valid = false;
		}
		
> How do you check if the user input is actually a string or an integer?

Any input can be treated as a sequence of characters: a string.
We could read the input as a string and then check if the string has the form of a valid integer to some base.

For instance:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
#include <iomanip>

bool is_int( std::string str, int base = 0 ) // note: if base == 0, base is auto-detected
{
    std::size_t pos = 0 ;
    try
    {
        // http://en.cppreference.com/w/cpp/string/basic_string/stol
        std::stoi( str, std::addressof(pos), base ) ;
        return pos == str.size() ; // true if the entire string was consumed
    }
    catch( const std::exception& )
    {
        return false ;
    }
}

int main()
{
    for( std::string str : { "0", "-0", "12ab", "-0x12ab", "-00123", "0193", "123x", "#45" } )
    {
       std::cout << std::setw(8) << str << " : " << std::boolalpha
                 << std::setw(6) << is_int(str) << ' ' << is_int( str, 10 ) << '\n' ;
    }

    std::string str ;
    std::cin >> str ;
    std::cout << std::setw(8) << str << " : " << std::boolalpha
                 << std::setw(6) << is_int(str) << ' ' << is_int( str, 10 ) << '\n' ;
}

http://coliru.stacked-crooked.com/a/cbbd6f277a4c49ea
Last edited on
Thank you, that is very helpful references.

Topic archived. No new replies allowed.