0

I am creating an oregon trail clone as a proof of concept type thing, and for some reason the loop of the function I determined before int main isn't looping, and just not doing anything.

using namespace std; int debuginput; string response; int loop = 0; void commands () { if (response == "cmd") { cout << "what would you like to do? type 'help' to get a list of commands." << endl; cin >> response; if (response == "start") { loop = 1; } else { loop = 0; } if (response == "test") { cout << "test"; } } } int main () { cin >> response; do { commands (); } while (loop == 0); /*-------------------------------------------------*/ } 

Basically, whenever I call the commands function to loop, I enter one command and it doesn't loop to let me put in another command.

9
  • 2
    Please apply consistent indentation. Commented Oct 7, 2020 at 13:14
  • 2
    ericlippert.com/2014/03/05/how-to-debug-small-programs Commented Oct 7, 2020 at 13:15
  • Looks like you need to reorder the comparisons. Commented Oct 7, 2020 at 13:16
  • 1
    @PiotrAdamMilewski The local loop variable is set to 1 and it won't affect the loop. Commented Oct 7, 2020 at 13:17
  • 2
    please read about minimal reproducible example. If I had to debug this code, the very first thing I would do is remove everything but 1-2 lines of code that let me observe if the loop is executed or not Commented Oct 7, 2020 at 13:17

1 Answer 1

1

In this piece of code inside your commands function:

if (response == "start") { int loop = 1; } 

you create a new variable with name loop on the stack, set it to 1 and then it immediately gets destroyed. You shadow the global variable loop with this.

I assume the correct variant would be:

if (response == "start") { loop = 1; } 

If you type in start it will update the loop variable and then the do while loop will end. If this is not what you want you should change the condition like that:

void commands() { // ... cin >> response; if (response == "start") { loop = 1; } else { loop = 0; } } do { commands(); } while (loop == 1); 
Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't that guarantee that the loop ends?
My compiler auto-connects things like if and else statements and brackets, hence the indentation as it doesn't carry over into text.
Also, even if that fixes my start, it won't repeat when not continuing.
@flying, please, take a look at the updated answer. Maybe it will be of some help.
It improved the code, but it still won't loop. I will edit this with a more simplified version of the code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.