Making a display menu and asking user to choose one and error check to keep asking until one of the three are chosen

Im trying to make it where you choose either 1,2, or 3 and if you don't choose one of those then it will repeat and ask you to try again basically.
Im unsure if I need to do just a while loop or not to make this work out.


char start_game ()
{
char choice;
cout <<" 1) New Game 2) Load Game 3) Quit\n"
do
{
cout << "Enter 1,2, or 3:\n"
cin >> choice

while (choice != '1' && choice != '2' && choice! = '3')
}
return choice;
}
Getting and validating user input is an example of a loop where the exit condition is in the middle of the loop. You'll find that the code is much cleaner if you write it that way rather than trying shoe-horn it into a traditional loop.
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
#include <iostream>

using std::cin;
using std::cout;

// Prompt the user for an integer value using "prompt".
// Validate that the choice is in the range [low, high].
// Reprompt if they enter a non-number or invalid value
int getChoice(const char *prompt, int low, int high)
{
    int result;
    while (true) {
	cout << prompt;
	if (cin >> result) {
	    if (low <= result && result <= high) {
		return result;
	    } else {
		cout << "The value must be between " << low
		     << " and " << high << '\n';
	    }
	} else {
	    // non-number entered
	    cout << "That isn't a number\n";
	    cin.clear();	// clear the error
	    cin.ignore(1000000, '\n'); // skip to end of line
	}
    }
}

int
main()
{
    cout << " 1) New Game 2)Load Game 3) Quit\n";
    int choice = getChoice("Enter 1,2, or 3:\n", 1, 3);
    cout << "You choose " << choice;
    return 0;
}

 1) New Game 2)Load Game 3) Quit
Enter 1,2, or 3:
4
The value must be between 1 and 3
Enter 1,2, or 3:
0
The value must be between 1 and 3
Enter 1,2, or 3:
four
That isn't a number
Enter 1,2, or 3:
3
You choose 3
Topic archived. No new replies allowed.