我创建了一个基于文本的游戏来帮助提高我的 C++ 技能,因为我对它还很陌生。我正在尝试学习所有基础知识。
这是程序。在 switch 语句中,如果一个人要选择“3”,它会广播一个错误,说你只能选择“1”或“2”。 ** 问题是程序会继续进行,不会让用户重新选择。这与选择困难症有关。
在玩家选择有效选择之前,我用什么方法强制程序停止?
谢谢!
#include <iostream>
using namespace std;
int main()
{
cout << "\tWelcome to my text based game!\n";
char userName[100];
cout << "\nPlease enter your username: ";
cin >> userName;
cout << "Hello, " << userName << "!\n\n";
cout << "Please pick your race: \n";
cout << "1 - Human\n";
cout << "2 - Orc\n";
int pickRace;
cout << "Pick your race: ";
cin >> pickRace;
switch (pickRace)
{
case 1:
cout << "You picked the Human race." << endl;
break;
case 2:
cout << "You picked the Orc race." << endl;
break;
default:
cout << "Error - Invalid input; only 1 or 2 allowed!" << endl;
}
int difficulty;
cout << "\nPick your level difficulty: \n";
cout << "1 - Easy\n";
cout << "2 - Medium\n";
cout << "3 - Hard\n";
cout << "Pick your level difficulty: ";
cin >> difficulty;
switch (difficulty)
{
case 1:
cout << "You picked Easy" << endl;
break;
case 2:
cout << "You picked Medium" << endl;
break;
case 3:
cout << "You picked Hard" << endl;
break;
default:
cout << "Error - Invalid input, only 1,2 or 3 are allowed" << endl;
}
return 0;
最佳答案
你需要使用循环。将输入和后面的开关包裹在一个循环中,并在输入有效时跳出循环。
关于c++ - 如果玩家输入无效选择,我如何防止程序继续?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7212814/