Switch statement looping

This is my switch statement looping (that i found on google) where ask users to enter numbers from 1 to 4, if users entered other numbers then loop back, but the problem is if users enter other than integers(char, symbol), it will cause a infinite loop, how should i improve this?
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
  bool valid;
    do{
    int n1;
    cout << "\nPlease select one service from above: ";
    cin >> n1;

    switch (n1) {
    case 1:
        cout << "XX" << endl;
        valid = true;
        break;
    case 2:
        cout << "XX" << endl;
        valid = true;
        break;
    case 3:
        cout << "XX" << endl;
        valid = true;
        break;
    case 4:
        exit(0);
        break;
    default:
        cout << "\nPlease enter numbers only from 1 to 4" << endl;
        valid = false;
        break;
    }
} 
while (!valid);
If the user enters something other than an integer, then that will be left in the buffer. You need to empty that buffer.

https://stackoverflow.com/questions/5131647/why-would-we-call-cin-clear-and-cin-ignore-after-reading-input
If the user enters something other than an integer, then n1 will remain uninitialized.

I'd separate the prompting from the computing. See get_number() by JLBorges in this post:
http://www.cplusplus.com/forum/beginner/182134/
Topic archived. No new replies allowed.