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?
Expand|Select|Wrap|Line Numbers
- // 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: