you've declared both
choice
and
temp
as
int therefore the expression
if(typeid(choice) != typeid(temp))
will always be false.
typeid is an operator which determines the static type of a variable at compile time, it has no knowledge of anything you do at runtime (such as user input), so it can't help you.
If you use
cin >> choice
and the user types in something which won't fit into an
int variable, then the internal "fail" flag which belongs to
cin
will be set to
true, and you'll not be able to do anything with cin until you've cleared the error state and discarded whatever bad data was waiting for you.
One option would be to perform your check as you're getting the data with
if( cin >> choice )
then if it fails, use a combination of clear() to reset the state and ignore() to discard any bad data left waiting for you:
1 2
|
std::cin.clear();
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
|
Although letting cin fail in the first place usually isn't ideal IMO; A better way would be to use a string, which is capable of storing any kinds of characters (cin is less likely to fail if you're getting a string), then do a checked conversion using a local stringstream object instead.
This has the advantage of avoiding the need to reset cin every time (it shouldn't matter if a local stringstream object has its fail flag set)
Example of a reliable checking/conversion function using a stringstream:
1 2 3 4 5 6 7 8 9 10
|
bool convert( const std::string& str, int& n )
{
std::istringstream buffer( str );
bool success = false;
if( buffer >> n )
{
success = true;
}
return success;
}
|