Exception handling

How to try and catch this error?
1
2
3
4
5
6
     do
    {
        cout << "Please enter number of rows of matrix: ";
        cin >> rows;
    }
    while ( rows <= 0 );


if character is enterd an infinite loop appeares

any help?
Check stream state after reading:
1
2
3
4
5
6
7
8
std::cin >> rows;
if(std::cin.fail()) { //If reading is unsuccessull
    std::cin.clear(); //Clear error state flag
    while(::isspace(std::cin.get()))
        ; //Skip offending input
    //Alternative with slightly different behavior:
    //std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
Other way is to make cin throw an exception on failure and either catch it or allow it to propagate:
1
2
3
4
5
6
7
std::cin.exceptions((std::istream::failbit);
//...
try {
    std::cim >> rows;
} catch(std::ios_base::failure &e) {
   //handle exception
}
Works, Thanks
Topic archived. No new replies allowed.