How do I clear cin when wrong type is entered?

This week I'm learning about exception handeling and I'm using try,throw,catch.
When I get a char instead of an int I'm throwing that...
the problem starts when I try to get new input.

I've read that there is junk left in cin in this case so...
How do I clear out the junk so that I can get new input?

Here's a portion of my program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream> //allows program to perform input and output

using std::cout;  //Program uses cout
using std::cin;   //Program uses cin
using std::endl;  //Program uses endl

	
 void getInput (int& x )
{
	cout<<"enter nonnegative integer: ";
	if (!(cin>>x)) throw " not a number ";
	if (y<0)throw " negative number ";
}

 
int main()
{	
	// variable declarations
	int x;
	try
	{
	getInput(x);
	}
	catch ( char * str )
	{
		cout<<str<<endl;
		getInput(x);  //works with negative number, not with alpha
	}
	cout<<x<<endl;

		system("PAUSE");

	return 0;  //indicate that program ended successfully

}  // end function main 


Thanks in advance...
Put a cin.ignore(numeric_limits<streamsize>::max(), '\n'); in there.

It will toss everything up to (and including I think) the newline in the buffer. Btw, if you second getInput throws again, then you won't catch the error.
Don't forget to cin.clear(); to clear the iostate flags...
Thanks I seem to have gotten it to work.
I had to throw in cin.sync() also.
I didn't know how to comment these 'cus I don't know what they do.

1
2
3
4
cin.ignore(numeric_limits<streamsize>::max(), '\n');	//clears cin after error
cin.clear();					//clears cin after error
cin.sync();					//clears cin after error


firedrako, you're right it won't catch a second error.

Thanks again,
Curt
Topic archived. No new replies allowed.