Checking input data type

Hi,

Is there a quick way of checking the data type of things?
I use a cin to get user input, and the thing that it's stored to is defined to be an integer. However, if I input things that are not integers, like "INTEGER", it goes crazy.
That is, I do something like this:
1
2
3
4
5
int number;
while(number!=1 && number!=0)
{
   cin >> number;
}

What happens is that if I input integers, it behaves reasonable, but if I input other kinds of things it just loops forever without stopping.

Thus, I wanted to write a couple of quick lines that checks if the input is indeed an integer (which is what I need), and if not, rejects the input.

Is that something that can be checked relatively easily (or in any way)?

Thanks!
Normally the operator>> call is placed in the loop condition. That way the loop will stop if it read failed for some reason.
1
2
3
4
5
int number;
while(cin >> number && number!=1 && number!=0)
{
	// ...
}


If you don't want the loop to stop you could put the call to operator>> inside an if statement and if it fails you call cin.clear() to clear the error state. This is needed or otherwise all read operations on cin will fail. Also call cin.ignore to discard the rest of the line. This is needed to get rid of the invalid input or otherwise it will just fail next time you try to read it anyway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int number;
while(number!=1 && number!=0)
{
	if (cin >> number)
	{
		// ...
	}
	else
	{
		cin.clear();
		cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
	}
	
}
Last edited on
Thanks! :)
Topic archived. No new replies allowed.