Restart a switch statement?

I can't find a way to make it restart if case default is true. Here is an example of my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int answer;
	cout << "What is in your bag?\n\n";
	cout << "1. A long sword\n";
	cout << "2. A short sword\n";
	cin >> answer;
	switch (answer)
	{
	case 1:
		cout << "You grab the long sword.\n";
		break;
	case 2:
		cout << "You grab the short sword.\n";
		break;
	default:
		cout << "Enter either 1 or 2 for your option.\n";
		break;
	}

I'd like it to go back to "cin >> answer;" if you enter something other than 1 or 2. Help is appreciated.
Last edited on
Here you go:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int answer;
bool done = false;

do {
    cout << "What is in your bag?\n\n";
    cout << "1. A Longsword\n";
    cout << "2. A Short Sword\n";
    cin >> answer;

    switch(answer) {
        case 1:
            cout << "You grab the Longsword.\n";
            done = true;
            break;
        case 2:
            cout << "You grab the Short Sword.\n";
            done = true;
            break;
        default:
            cout << "Enter either 1 or 2 for your option.\n";
            break;
    }
} while(!done);
Last edited on
Thank you. Didn't think about using do-while.
Last edited on
I ran into another issue, when i type a letter instead of a number, it spams this:


What is in your bag?

1. A long sword
2. A short sword
Enter either 1 or 2 for your option


Repeatedly, (or infinitely).
Last edited on
I still need help with this..
When std::cin fails to parse input correctly (say the user enters a character when the program was expecting an integer), certain internal flags are set, and it refuses to do anything else until it is reset.

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
...
#include <limits>
...

int answer;
bool done = false;

do {
    cout << "What is in your bag?\n\n";
    cout << "1. A Longsword\n";
    cout << "2. A Short Sword\n";
    cin >> answer;

    if(cin.fail()) { // Failed to parse input correctly
        cin.clear(); // Clear the internal flags
        cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // Ignore the rest of the buffer
    }

    switch(answer) {
        case 1:
            cout << "You grab the Longsword.\n";
            done = true;
            break;
        case 2:
            cout << "You grab the Short Sword.\n";
            done = true;
            break;
        default:
            cout << "Enter either 1 or 2 for your option.\n";
            break;
    }
} while(!done);
Thank you very much kind fellow coder :3 Everything is good now.
Topic archived. No new replies allowed.