Search code examples
c++textgoto

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


I am very new to C++ and have decided to start with a basic text based RPG. I have been using this site as a reference; 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();

This is the code that the site shows as a reference but I have had some issues with it. Primarily with the "goto" command only working for incorrectly inputted integers. If you enter a letter character there, it makes an infinite loop instead.

During my search for a solution to the problem I found a great deal of animus towards the "goto" function. Modern code has essentially refuted it's use as I understand it. So at this point I am looking for a different function that can perform that task of redoing the cin function upon inputting an unusable character.

I am entirely willing to use a completely different structure or system if there isn't a natural replacement for that command in this context.


Solution

  • Best substitute for goto

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

    That's what we in the trade call a "loop". Any flavor of loop structure is fine for this example, but this is a rare case where do-while is nice. A direct transformation:

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