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.
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);
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.
...
#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);