How can I get my code to print "Invalid input"

How do I get my code to print “Invalid input” when I enter for example a character? when I enter a character my output is “The number is 0”.

int main() {
int number;
cout << "Enter an integer: ";
cin >> number;

if (number > 0)
    cout << number << " is a positive integer";
else if (number < 0)
    cout << number << " is a negative integer";
else if (number == 0)
    cout << "The number is 0";
else
    cout << "Invalid input";

return 0;

}

The top voted answer here does a good job of explaining:

Basically invalid input puts the cin into an error state which you can check by using if !(cin) it is also returned by cin >> someVariable so you can do both at the same time. You also need to clear the error state properly so that you can use cin again.

2 Likes