user3532547
user3532547

Reputation: 87

Goto not working correctly C++

I recently started learning c++, and I am just testing what I know by making a terrible little game.

I want to jump back in my code, so I learnt about a goto statment. Here is my code(not all of it, just the goto bit)

moving:

if(moveChoice == "Forward"){
    cout << "You moved Forward" << endl;
    moveChoice = "";
    if(firstTargetRand == 2){
        cout << "You encountered a tree!" << endl;
    }if(firstTargetRand != 2){
        cout << "goto init" << endl;
        goto moving;
    }
}

Now "goto moving" is getting called ( checked with cout goto init ) but this isn't working. I know this is prob a really stupid mistake, but I can't see anything wrong with it

Upvotes: 0

Views: 372

Answers (1)

Smurfton
Smurfton

Reputation: 189

Well, first of all, I feel obligated to mention that goto is frowned upon for pretty much any use, and like the comments say, this is prime loop material.

Your problem is that you are checking if moveChoice == "Forward", then setting moveChoice to "", then going back, and then moveChoice == "Forward" always returns 0.

If you really want the goto, try this:

if(moveChoice == "Forward"){
    moving:
    cout << "You moved Forward" << endl;
    moveChoice = "";
    if(firstTargetRand == 2){
        cout << "You encountered a tree!" << endl;
    }else{
        cout << "goto init" << endl;
        goto moving;
    }
}

If you aren't terribly partial to the goto, try this:

while(moveChoice=="Forward"){
    cout << "You moved Forward" << end1;
    if(firstTargetRand == 2){
        cout << "You encountered a tree!" << end1;
        moveChoice = "";
    }else{
        cout << "goto init" << end1;
    }
}

Upvotes: 4

Related Questions