我发布了一个关于如何使用 if else 语句获取用户输入(例如是或否)来控制程序流程的问题,我得到了答案,现在我离完成这项工作又近了一步,但是又出现了另一个问题,我真的需要允许多个输入,例如这是我正在尝试的:
if (input == ("YES" || "yes" || "y" || "Yes" || "Y"))
{
cout << "you said yes" << endl;
}
else if (input == "NO", "no", "n", "No","N")
{
cout << "you said no" << endl;
}
else
{
cout << "ERROR!!!" << endl;
}
Kiril Kirov 发布了这段代码,可以提供帮助:
if( std::string::npos != input.find( "no" ) )
但我无法让它工作,罗杰佩特建议这样做:
if (prompt && cin.tie()) {
*cin.tie() << prompt << (default_yes ? " [Yn] " : " [yN] ");
但是我从未尝试过,因为它的复杂性远远超出了我的理解。我希望有一个初学者程序员可以理解的解决方案,或者我只是一个非常慢的学习者
编辑:我做了这个修改,但它仍然没有比以前更好,如果我给出错误的情况,它会转到其他(错误)并且没有地方可以添加更多单词,(例如 NO N no No):
cout << "\nYES or NO" << endl;
string input ="";
cin >> input;
if ( std::string::npos != input.find( "yes" ) )
{
cout << "you said yes" << endl;
}
else if ( std::string::npos != input.find( "no" ) )
{
cout << "you said no" << endl;
}
else
{
cout << "ERROR!!!" << endl;
}