简体   繁体   English

条件语句简化-C ++

[英]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? 减少此代码中的条件的最佳方法是什么,是只是简单地实现Boost库以进行字符串比较还是有另一种方法呢? I would much more prefer to avoid using boost if possible. 如果可能的话,我会更喜欢避免使用boost。

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

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")
//...

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. 由于您没有在第一个if语句中检查'yEs'作为可能的情况,因此以下内容并不完全相同,但这可能与您要查找的内容大致相同。 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. 我以重命名question的自由来answer ,在这种情况下似乎更合乎逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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