Reputation: 129
This is probably a very newbie question but I am just practising classes for C++ and cannot seem to get this do while loop to end under a boolean condition.
int main()
{
bool endgame = false;
string x;
int choice;
cout << "please choose the colour you want your bow to be:\n";
cin >> x;
Bow bow1(x);
do
{
cout << "please choose what you would like to do\n";
cout << "(1 draw bow\n(2 fire bow\n(3 end game";
cin >> choice;
if (choice == 1)
{
bow1.Draw();
}
else if (choice == 2)
{
bow1.Fire();
}
else
{
endgame = true;
}
}
while (choice > 0 || choice < 3 || endgame == true);
return 0;
}
Upvotes: 0
Views: 1936
Reputation: 55649
Since you're using OR (||
):
0 < choice < 3
, the loop will obviously continue since both choice > 0
and choice < 3
are true, this is what we want.choice >= 3
(say 10), the loop will continue since choice > 0
is truechoice <= 0
(say -1), the loop will continue since choice < 3
is true.Thus the loop will always continue for any value of choice
(regardless of endgame
's value).
Also, the loop will continue (instead of stopping) while endgame
is true
, which is set as soon as choice
is given a value of not 1 or 2.
If you make it AND (&&
) and reverse the endgame
check, it should work:
while (choice > 0 && choice < 3 && endgame == false);
But really the choice > 0 && choice < 3 &&
is unnecessary since you're setting endgame
once either of those conditions hold.
while (endgame == false);
This can be simplified to:
while (!endgame);
Upvotes: 4
Reputation: 1039
Here:
if(endgame) break;
Try putting that at the end of your loop.
Upvotes: 0
Reputation: 19
What you want is to stay in the loop as long as your endgame
is false, so you only need to change your test in the while statement like this:
while (choice > 0 || choice < 3 || endgame == false)
Upvotes: 0
Reputation:
do {
if (exit_condition)
endgame = true;
} while (endgame == true);
This will set endgame
to true when the exit condition is met, then loop back, because you check for endgame
being true and not false. You want
} while (!endgame);
instead.
Upvotes: 3