作为初学者在基于文本的角色扮演游戏中使用 C++ 中 goto 的最佳替代品

Best substitute for goto in C++ as beginner for use in text-based RPG

我是 C++ 的新手,因此决定从一个基本的基于文​​本的 RPG 开始。我一直在使用这个网站作为参考; https://levelskip.com/classic/Make-a-Text-Based-Game#gid=ci026bcb5e50052568&pid=make-a-text-based-game-MTc0NDU2NjE2MjQ1MDc3MzUy

system("cls");
int choiceOne_Path;
cout << "# What would you like to do?" << endl;
cout << "\t >> Enter '1' to follow the Chief?" << endl;
cout << "\t >> Enter '2' to find your own path?" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if(choiceOne_Path == 1)
{
    cout << "\n!!!----------------------Chapter One: Escape----------------------!!!" << endl;
    cout << "\nYou: Where are we going?" << endl;
    cout << "Chief: Soon you will know. Just follow me." << endl;
    cout << "# You run behind the chief." << endl;
}
else if(choiceOne_Path == 2)
{
    cout << "\n!!!----------------------Chapter One: Escape----------------------!!!" << endl;
    cout << "\nYou: I am going to find a way out!" << endl;
    cout << "Chief: You are insane. You will get killed out there." << endl;
    cout << "You: I have my secrets and I know my way out." << endl;
    cout << "# You jump over the nearby broken fence" << endl;
    cout << "# and run off towards the City Wall." << endl;
}
else
{
    cout << "You are doing it wrong, warrior! Press either '1' or '2', nothing else!" << endl;
    goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();

这是网站显示的参考代码,但我遇到了一些问题。主要使用“goto”命令,仅适用于错误输入的 整数 。如果你在那里输入一个字母字符,它就会变成一个无限循环。

在我寻找问题解决方案的过程中,我发现对“goto”函数有很大的敌意。据我所知,现代代码基本上驳斥了它的用途。所以在这一点上,我正在寻找一个不同的函数,它可以在输入一个不可用的字符时执行重做 cin 函数的任务。

如果在这种情况下该命令没有自然的替代品,我完全愿意使用完全不同的结构或系统。

Best substitute for goto

retry:
// accept input
if (/* input predicate */)
{
    // ...
}
else
{
    // ...
    goto retry;
}

这就是我们在行业中所说的“循环”。任何形式的循环结构都适用于此示例,但在这种情况下 do-while 很好用的情况很少见。直接变换:

do
{
    // accept input
    if (/* input predicate */)
    {
        // ...
        break;
    }
    else
    {
        // ...
    }
} while(true);