problem with (try catch)

hi guys

please see this code:

1
2
3
4
5
6
7
8
9
int x;
try
{
cin>>x;
}
catch(...)
{
cout<<"input error";
}


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

i am sorry because I dont speak good English

help me please
Failed input won't throw an exception by default
You can check if the last input operation succeeded using cin.good()
Or modify exceptions to force cin throw when something went wrong
http://www.cplusplus.com/reference/iostream/ios/good/
http://www.cplusplus.com/reference/iostream/ios/exceptions/
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.

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
36
37
38
39
40
41
42
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

template< typename T >
T grab(const char * 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(const char * 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;
}
Last edited on
thanks a lot
but this is too complex and very long
Can I ask you to write simple and short ?
grateful
i understand
my problem solved
thanks guys
Topic archived. No new replies allowed.