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

**URL:** <https://forum.codewithmosh.com/t/how-can-i-get-my-code-to-print-invalid-input/15276>\
**Category:** C++\
**Created:** [September 19, 2022, 11:19am UTC](https://forum.codewithmosh.com/t/how-can-i-get-my-code-to-print-invalid-input/15276 "2022-09-19T11:19:48Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Annern99](https://avatars.discourse-cdn.com/v4/letter/a/54ee81/32.png) [@Annern99](https://forum.codewithmosh.com/u/Annern99)\
**Post date:** [September 19, 2022, 11:19am UTC](https://forum.codewithmosh.com/t/how-can-i-get-my-code-to-print-invalid-input/15276/1 "2022-09-19T11:19:48Z")

</div>

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;

```

}

---

<div class="post-metadata">

**Author:** ![jmrunkle](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.codewithmosh.com/jmrunkle/32/3765_2.png) [@jmrunkle](https://forum.codewithmosh.com/u/jmrunkle)\
**Post date:** [September 19, 2022, 1:51pm UTC](https://forum.codewithmosh.com/t/how-can-i-get-my-code-to-print-invalid-input/15276/2 "2022-09-19T13:51:58Z")

</div>

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

> <https://stackoverflow.com/questions/10349857/how-to-handle-wrong-data-type-input>

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.
