I am trying to make a try catch where if a user enters a char into an int it catches it and returns an error message. How do I specify catch a char in the catch block?
#include <iostream>
usingnamespace std;
int main()
{
cin.exceptions( ios::failbit );
int n;
cout << "Enter an integer (but really enter a character): ";
try
{
cin >> n;
}
catch (const exception& e)
{
cout << "Good job! You entered the wrong thing!\n""The error message I got was: \"" << e.what() << "\"\n";
return 0;
}
cout << "What?! You entered the integer " << n << ".\n";
return 1;
}
Hope this helps.
[edit]
After posting this, I remember that you should be aware that this approach has all the same troubles as doing it without the exceptions. Try entering something like "12abc" to see what I mean.