CIN and exception handling
Hi there... I have an assignment this week in an OOP class and the program already demonstrates simple exception handling according to the assignment requirements. This question is more for my own benefit... I had a problem with the proper use of the failbit a few weeks ago:
Failbit trouble
I received some great assistance and thought that I had this concept down so I used a similar section of code to detect non-int values for this assignment. When the program is run, the program catches decimal values and any other inputs consisting of a number followed by anything non-int. However, the user hitting a letter or and non-numeric character first results in an untimely exit... :mad:
There is more to the code including another throw and catch for long number errors but I removed the parts that were not pertinent to this problem... Suffice to say, I used #includes to avoid having to type std:: and the actual throw constructors are outside of main and seem to work fine...
Code:
int main()
{
int num; // user-specified ID
cout << "Enter a positive integer ID number (max 6-digit) for validation" <<
"\n(end-of-file to end): ";
// user ID input
while ( cin >> num ) {
try {
// Tests input for invalid data format
if ( cin.fail() || cin.get() != '\n' ) {
cin.clear();
cin.ignore(5000,'\n');
throw InvalidFormatException();
} // end if
} // end try block
// exception handler handles invalid format exceptions
catch ( InvalidFormatException &InvalidFormatException ) {
cout << "\nAn exception occurred: " <<
InvalidFormatException.what() << endl;
} // end catch
cout << "\nEnter a positive integer ID number (max 6-digit) for validation" <<
"\n(end-of-file to end): ";
} // end while
cout << endl;
return 0; // terminate normally
} // end main
I am stumped as to what is happening here... I thought that a non-numerical input would result in the failbit setting and throwing the exception... Instead, all I get is 'Press any key to continue' and POOF!
From what I understood after reading the thread I listed above and this one , it appears to me that this type of input should be caught with that 'if' check...
Any assistance would be appreciated... Thanks in advance...