Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I write an eloquent continue?

Tags:

c++

loops

So its often come up in my classes that i need to be able to have a program where the user can do things multiple times.

so I write something like

boolean continue=true;

while (continue) {
    //do code
    boolean isAnswerGood=false;
    while (!isAnswerGood) {
        cout << "Do you wish to continue" << endl;
        string answer;
        getline(cin, answer);
        if (answer=="y") //or something else
            isAnswerGood=true;
        else if (answer=="n") {
            isAnswerGood=true;
            continue=false;
        } else 
            cout << "That wasnt "y" or "n" please type something again" << endl;
    }
}

This seems bloated and a lot of code for something so simple. Im willing to think outside of the box with this one, so if anyone can give me a clue as to a better solution to this, id appreciate it.

like image 234
Mr. MonoChrome Avatar asked Nov 24 '25 03:11

Mr. MonoChrome


1 Answers

Break it into separate functions. (Almost always the answer to "how do I write an eloquent...?")

For example:

do {
  // something
} while (UserWantsMore());

/////////

bool UserWantsMore() {
  std::string answer = GetAnswer("Continue?");
  while (!GoodAnswer(answer))
    answer = GetAnswer("Please answer 'yes' or 'no'!");
  return IsAnswerYes(answer);
}

bool GoodAnswer(const std::string& answer) {
  return !answer.empty() && (answer[0] == 'y' || answer[0] == 'n');
}

bool IsAnswerYes(const std::string& answer) {
  return !answer.empty() && answer[0] == 'y';
}

std::string GetAnswer(const char* prompt) {
  std::cout << prompt << std::cend;
  std::string answer;
  std::getline(std::cin, answer);
  return answer;
}
like image 154
rici Avatar answered Nov 25 '25 18:11

rici



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!