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
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.
#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(constchar *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