TrevorLee
TrevorLee

Reputation: 231

Conditional Statement Simplification - C++

What would the best way be of reducing my conditions in this code, is it to simply implement the Boost library for a string comparison or is there another way of doing it? I would much more prefer to avoid using boost if possible.

How could said question be implemented on the following code?

cout << " Please Enter An Answer Of Yes(Y) or No(N):";
string question; cin >> question;

if (question == "yes" || question == "Yes" || question == "Y" || question == "y" || question == "YEs" || question == "YES" || question == "yeS" || question == "yES") 
{
    cout << "You said yes!" << endl;
    return 1;
} 
else if (question == "No" || question == "NO" || question == "nO" || question == "N" || question == "n")
{
    cout << "You said no!" <<endl;
    return 0;
}  
else 
{
    AskAQuestion();
}

Upvotes: 0

Views: 110

Answers (2)

NathanOliver
NathanOliver

Reputation: 180415

It might not be the most efficent solution but if you convert the entire string to lower case then you only need to check against the word and the letter instead of all the possible permutation. So if you have

void make_lowercase(std::string& data)
{
    std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}

Then

cout << " Please Enter An Answer Of Yes(Y) or No(N):";
string question; cin >> question;

if (question == "yes" || question == "Yes" || question == "Y" || question == "y" || question == "YEs" || question == "YES" || question == "yeS" || question == "yES") 
//...

Becomes

cout << " Please Enter An Answer Of Yes(Y) or No(N):";
string question; 
cin >> question;
make_lowercase(question);

if (question == "yes" || question == "y")
//...

Upvotes: 2

Ton van den Heuvel
Ton van den Heuvel

Reputation: 10528

The following does not do exactly the same since you did not check 'yEs' as a possible case in the first if statement, but this is probably along the lines what you are looking for. It is based on lower casing the answer of the user first before checking the answer, to reduce the number of cases to check.

#include <algorithm>
#include <cctype>

...

std::cout << "Please Enter An Answer Of Yes(Y) or No(N): ";
std::string answer; std::cin >> answer;
std::transform(answer.begin(), answer.end(), answer.begin(), std::tolower);

if (answer == "yes" || answer == "y")
{
  std::cout << "You said yes!\n";
  return 1;
}
else if (answer == "no" || answer == "n")
{
  std::cout << "You said no!\n";
  return 0;
}
else
{
  AskAQuestion();
}

I took the liberty of renaming question to answer, seems more logical in this context.

Upvotes: 1

Related Questions