Validate input is not a character?

How do I validate whether an input is not a character?
For example:
1
2
3
int number;
cout << "What number (-1 to exit program)? ";
cin >> number;

Number can equal -1 and any positive integer. Number cannot equal a character or any number < -1. I need to use a while loop for this one.
Last edited on
I'm assuming you are talking about integers only. From your code snippet it looks that way..

regardless, cin will return false if you try and read something into the wrong datatype. so, :

if (cin >> number) { ... }

could work.

Ken
kbarrett, What does if (cin >> number) {...} do? I'm new to C++ and just finished learning about loops and if's. Thanks for the reply.
Last edited on
cin captures user input from the keyboard. There are other operations that are used to capture data in other interesting ways.. but cin just gets a hunk of data (up to the first space) and puts it into the variable you give it.

if the variable number is an int, then cin >> number gets user input from the keyboard and tries to put it into the int number variable. If the user has entered something other than an int, then cin throws an error, which is detected with the if evaluation.
Thanks very much. I just tested that out. I never knew about it till now.
Topic archived. No new replies allowed.