Switch statement question

Hi, I am having an issue with a switch statement i was hoping someone could maybe help out with. The input i wish the user to give is a number, and when this is done, the switch works fine, however, when a letter is given, the default statement prints, but rather than just printing the once, like I thought it would, it repeatedly prints, and does not stop.

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

void menu()
{
int i;
cout << "1 : Create user\n";
cout << "2 : login\n;

 cin >> i;
	switch (i)
	{
	case 1:
		inSyd.CU();
		menu(user);
		break;
	case 2:
		logSys.log();
		menu(user);
		break;
	case 3:
		logSys.ptint();
		menu(user);
		break;

	default:
		cout << "Invalid\n";
		menu();
		break;
	}
} 
When you try to read letters as a number the stream "goes bad" and needs to be "cleared" before it can be used again. You also need to get rid of the letters since they will have been left in the buffer.

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
43
#include <iostream>
using namespace std;

void menu()
{
    cout << "\n1 : one\n"
            "2 : two\n"
            "3 : three\n"
            "4 : quit\n\n";

    int i;
    cin >> i;

    switch (i)
    {
    case 1:
        cout << "one\n";
        break;
    case 2:
        cout << "two\n";
        break;
    case 3:
        cout << "three\n";
        break;
    case 4:
        cout << "quit\n";
        return;
    default:
        if( cin.eof() )
            return;
        cout << "Invalid\n";
        cin.clear();
        cin.ignore(9999, '\n');
        break;
    }

    menu();
} 

int main()
{
    menu();
}

This still allows a number followed by a letter, like "1a", which will cause switch case 1 to execute and then the next cin will read (choke on) the letter. To deal with that it's best to read the input as an entire line first, then, using an istringstream, read the integer and ensure the line is blank after that.
Last edited on
When you try to input invalid data the input stream goes into a "fail" state, which makes all future attempts at input fail and well.

After every input, check for failure and cin.clear() it. The invalid data is still sitting in input, so you will need to extract it too.

Best course of action is to simply terminate on error and require your user to supply valid input.

Hope this helps.
thank you for the help. this has solved my issue. i am working through the code to understand it fully. thank you again.
Topic archived. No new replies allowed.