How to properly use cin.fail()?

Hello guys. For my final exam this year I must do a program, but I must protect it from dumb people. For example, I ask the user to enter an int, but he enters something like
dfsadfa
or
+*+-/*-
. I've heard that one way to prevent the user to make my program fail with such an input would be to use function
cin.fail()
. The thing is that i'm a very beginner and don't know what the stream nor the buffer is, so i don't know if i'm writing the code properly. Could you take a look at the following code to see if that's the structure i should use:

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
#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int x;
    bool right_input;
    
    do
    {
        cin >> x;
        cout << endl;
        
        if (cin.fail())
        {
            cout << "Unvalid input. Try again." << endl;
            cin.clear();
            cin.ignore(1000, '\n');
            right_input = false;
        }
        else
        {
            right_input = true;
        }
    } while (right_input == false);
    
     cout << "Right data type entered." << endl; 
    
    system("PAUSE");
    return EXIT_SUCCESS;
}


I would like to hear your comments! Thank you in advance.
Topic archived. No new replies allowed.