After a user inputs a char value for number two times, I do not receive any output when the program attempts to output the value of messageStr from within the catch block. It appears to be an empty string. Why?
From attempting to output the value of str at various locations, I think that somehow the value for str is being deleted after the first time through the loop. I don't know why this would happen. For some reason, including the initialization for str from inside the do/while loop works, as does including it in the global scope. But putting it inside the main() function scope appears not to work.
Ideas?
Here is the output I am getting as an example:
Line 8: Enter an integer: q
Line 18: The input stream is in the fail state.
Line 19: Restoring the input stream.
Line 8: Enter an integer: q
Line 18:
Line 19: Restoring the input stream.
Line 8: Enter an integer:
From attempting to output the value of str at various locations, I think that somehow the value for str is being deleted after the first time through the loop. I don't know why this would happen. For some reason, including the initialization for str from inside the do/while loop works, as does including it in the global scope. But putting it inside the main() function scope appears not to work.
Ideas?
Code:
// Handle exceptions by fixing the errors. The program continues to
// prompt the user until a valid input is entered.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int number;
bool done = false;
string str =
"The input stream is in the fail state.";
do
{
try
{
cout << "Line 8: Enter an integer: ";
cin >> number;
cout << endl;
if (!cin)
throw str;
done = true;
cout << "Line 14: Number = " << number
<< endl;
}
catch (string messageStr)
{
cout << "Line 18: " << messageStr
<< endl;
cout << "Line 19: Restoring the "
<< "input stream." << endl;
cin.clear();
cin.ignore(100, '\n');
}
} while (!done);
return 0;
}
Line 8: Enter an integer: q
Line 18: The input stream is in the fail state.
Line 19: Restoring the input stream.
Line 8: Enter an integer: q
Line 18:
Line 19: Restoring the input stream.
Line 8: Enter an integer:
Comment