在这段代码中减少我的条件的最好方法是什么,是简单地实现Boost库以进行字符串比较还是有另一种方法呢?如果可能的话,我会更希望避免使用Boost。
如何在以下代码中实现所说的问题?
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();
}
答案 0 :(得分:2)
这可能不是最有效的解决方案,但是如果将整个字符串转换为小写,则只需要检查单词和字母,而不需要检查所有可能的排列。所以如果你有
void make_lowercase(std::string& data)
{
std::transform(data.begin(), data.end(), data.begin(), ::tolower);
}
然后
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 << " Please Enter An Answer Of Yes(Y) or No(N):";
string question;
cin >> question;
make_lowercase(question);
if (question == "yes" || question == "y")
//...
答案 1 :(得分:1)
以下内容并不完全相同,因为您没有在第一个if语句中检查“ yEs”(可能的情况),但这可能与您要查找的内容大致相同。它是基于较低的用户在回答答案之前先回答用户的答案,以减少要检查的案例数。
#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();
}
我自由地将question
重命名为answer
,在这种情况下似乎更合乎逻辑。