It looks like the program exits due to this line:
Try printing the value of variable a before and after the if(a < 666) check (line 16). You'll find that it holds a junk value. This happens because a was not initialized and the attempt to assign a value on line 9 fails when the user enters a word.
When you enter an valid integer first, a gets an valid value. Your loop continues as long as a remains valid. Later attempts to change the value to "sad" fail, so it keeps the original value you assigned it.
From what I've learned so far, a common way to validate input is to include the cin operation within a conditional statement. For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
#include <iostream>
#include <limits>
using namespace std;
int main() {
int a;
cout << "enter an integer: ";
while (!(cin >> a)) // (cin >> a) == true if assignment successful
{
cout << "invalid input, please enter an integer: ";
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
}
cout << "thank you. your integer is " << a << '\n';
return 0;
}
| |
cin has internal flags that indicate it's status. If an attempt to read in fails for some reason, some of those flags are switched to indicate that cin didn't work. This applies to other input/output streams too, such an ifstream for reading from files.
To reset those flags, we can use cin.clear(). This lets us use cin again. It's possible that there's still characters in the stream, however, so we can use cin.ignore() to discard any lingering input.