Reputation: 11
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.
Upvotes: 0
Views: 75
Reputation: 1941
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);
Upvotes: 1