if user input an int(), not problem
but if user input a string or char , my Program gives me error
how can control this error with try cath???
this code that i write not work
thanks for cin.good()
but
can i want you modify exceptions to force cin throw when something went wrong?
can you write this code by throw?
thanks a lot .
If you want cin to throw when an error flag is active you have to call cin.exceptions in the way shown in the link.
If you want an exception for every kind of input failure call cin.exceptions ( ios::failbit | ios::badbit | ios::eofbit ); before you attempt any input
This may be a bit advanced for you, but here is a template that will allow you to grab valid input for any data type. The only exception is that it does not act like getline() and will not grab entire lines of text unless it is not separated by spaces.
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
template< typename T >
T grab(constchar * prompt);
int main(int argc, char** argv)
{
// This will grab an integer. Any other data type will result in an input failure.
int x = grab<int>( "Enter an integer: " );
cout << "You entered: " << x << endl;
return 0;
}
template< typename T >
T grab(constchar * prompt)
{
T thing;
std::istream::iostate old_state = cin.exceptions();
cin.exceptions(std::istream::failbit);
while(true)
{
try {
cout << prompt;
cout.flush();
cin >> thing;
cin.exceptions(old_state);
return thing;
} catch (std::istream::failure &e) {
cout << "Input failure. Please try again." << endl;
cin.clear();
cin.ignore(1024, '\n');
}
}
return thing;
}