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?
#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
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.