简体   繁体   中英

How do I end this do while loop?

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;
}

Since you're using OR ( || ):

  • If 0 < choice < 3 , the loop will obviously continue since both choice > 0 and choice < 3 are true, this is what we want.
  • However, if choice >= 3 (say 10), the loop will continue since choice > 0 is true
  • and if choice <= 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);
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.

Here:

if(endgame) break;

Try putting that at the end of your loop.

只要您的endgame是假的,您想要的就是保持循环,因此您只需要在while语句中更改测试,如下所示:

while (choice > 0 || choice < 3 || endgame == false)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM