作为初学者在基于文本的 RPG 中使用的 C++ 中 goto 的最佳替代品

问题描述

我对 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 函数的任务。

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

解决方法

goto 的最佳替代品

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

这就是我们业内所说的“循环”。任何形式的循环结构都适用于这个例子,但这是一种罕见的 do-while 很好的情况。直接转换:

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...