Reputation: 1
Im new to programing in a whole and I was wondering how I could loop my while loop. I'm making a calculator and i've gotten to a part where I have the program ask whether or not the user wants to end the program, if the user answers "Yes" the program will end; however I have noticed that if the user answers "No" the program will just keep on working and not ask the question again. Is there a way where I can have it ask the question again?
while (response != "Yes" && response != "No") {
cout << "Would you like to end the program? Yes or No" << endl;
cin >> response;
if (response == "Yes") {
calculator_running = false;
} else if (response == "No") {
calculator_running = true;
} else {
cout << "Please choose a valid response" << endl;
}
}
Upvotes: 0
Views: 70
Reputation: 17454
I have noticed that if the user answers "No" the program will just keep on working and not ask the question again
That's what you told the program to do!
If you don't want an entry of "No"
to end the loop, take it out of the condition:
while (response != "Yes") {
Or, use your boolean, which is a bit "cleaner" (but ultimately has the same effect):
while (calculator_running) {
Upvotes: 0
Reputation: 37512
Best practice is to split code to smaller pieces to keep concerns separated.
bool promptYesNo(const std::string& reason)
{
std::cin.clear(); // clear any error flags on cin
std::cout << reason << "\nType \"Yes\" or \"No\": ";
std::string answear;
while (std::cin >> answear) {
if (answear == "Yes") return true;
if (answear == "No") return false;
std::cout << "Please select \"Yes\" or \"No\": ";
}
// here standard input has ended, so terminating application:
std::exit(1);
}
while (!promptYesNo("Would you like to end the program?")) {
...
}
Note that std::cin.clear();
will protect you from invalid state of std::cin
. Most probably this is source of your problems. For example some part of program was reading int
value, but you have provided a letters. This setts error flags on cin
and any later reads will fail.
Upvotes: 1
Reputation: 17493
You need to put the calculator_running
to be checked in the while-part of the loopo, something like this:
calculator_running = true;
while (calculator_running)
...
Lke this, once you enter "Yes", that variable will be put to false, and you'll jump out of the loop.
The main trick with while-loops is that you always need to set the condition to true, just before you start the while-loop.
Upvotes: 0