c++ - 如果玩家输入无效选择,我如何防止程序继续?

标签 c++

我创建了一个基于文本的游戏来帮助提高我的 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/

相关文章:

c++ - 对象数组的释放?

c++ - 使用 avicap.dll 打开设置

c++ - C/C++ 中的位顺序

c++ - SDL_LoadBMP 只返回 NULL

c++ - Qt 定价(最新)

c++ - 在不压缩的情况下在opencv中保存帧

c++ - 可以将 std::pairs 的 std::vector 转换为字节数组吗?

c++ - 在 C++ 中以编程方式获取系统启动时间(Windows)

C++ 错误 - 预期主表达式在 'char' 和 'int' 之前

c++ - 第三人称相机翻转循环