do … while loop not breaking c++

  • A+

currently I'm having problems with this do ... while loop.

do {   // program code here     cout << "Would you like to run the program again?(yes/no)";     bool exit = false;     string strexit;     do {         getline(cin, strexit);         if (strexit == "no") {             exit = false;             break;         }         else if (strexit == "yes") {             exit = true;         }         else {             cout << "Enter yes to rerun the program, and no to exit./n";         };     } while (!exit);     system("cls"); } while (exit); return 0; } 

I researched online, how to break out of do ... while loops, and it's when the condition is true, it loops back again, but if its false it exits. So if you look at the code, if the user types in no, it sets exit = false, which takes it out of the bigger do while loop, where the break takes it out of the current do while loop. If the user enters yes, it changes exit to true, which breaks it out of the current do ... while loop, but it doesn't break out of the second.

My question is, (or what I need help with) is that when the user inputs 'no', it cannot exit the do ... while loops, and I'm severely confused as to why. (It loops back to the beginning of the program.)


In the (shortened) code

do {     bool exit = false;     // ... } while (!exit); 

you actually have two different symbols named exit. Inside the loop you have the variable. Outside of the loop, and used for the condition, you have the function std::exit. Which will be plain exit if you have using namespace std;.

The function exit when used in the condition will decay to a pointer to the function, and it will never be "false". So the condition !exit is always true and you have an infinite loop.

To solve this there are two things you need to do:

  1. Learn that using namespace std; is very bad practice

  2. Move the variable exit to be defined outside the loop. And you should really rename to something more descriptive it as well (the word "exit" is a little bit to general).


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: