I was wondering, how would I be able to compare a variable which is supposed to hold integer values, to times when it is passed a char value:
For example:
int i;
cin >> i;
if(i == integer)
execute a command;
else (if i == char)
do something else here;
Since x can’t hold a character value, would it just fail when someone tries to input a character value in i?
Get input into a string, then try to convert it to an integer (you have a myriad of options here,
boost::lexical_cast,std::istringstream,std::stoi, etc…). If the conversion succeeds, you have an integer, if it fails, you don’t. Here’s an example usingistringstream:If you don’t care what the input was in the case that it wasn’t an integer, you can just check for failure directly on input into an
int: