In your non-integer branch you are invoking further cin
methods so cin.good()
gets reset to true.
You could change your code to something like this:
while(1) { // <<< loop "forever"
cout << "Please enter an integer.";
cin >> n;
if (cin.good())
{
if (n < 0) {cout << "Negative.";}
else { cout << "Positive."; break; }
} // ^^^^^ break out of loop only if valid +ve integer
else
{
cout << "Not an integer.";
cin.clear();
cin.ignore(INT_MAX, '
'); // NB: preferred method for flushing cin
}
}
cout << "
done.";
or you can simplify it even further like this:
while (!(cin >> n) || n < 0) // <<< note use of "short circuit" logical operation here
{
cout << "Bad input - try again: ";
cin.clear();
cin.ignore(INT_MAX, '
'); // NB: preferred method for flushing cin
}
cout << "
done.";
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…