gpt4 book ai didi

c++ - 在C++中允许多种形式的 "yes"和 "no"的多种输入

转载 作者:太空狗 更新时间:2023-10-29 22:52:32 24 4
gpt4 key购买 nike

posted a question关于如何使用 if else 语句获取 YES 或 NO 等用户输入来控制程序的流程,我得到了答案,现在我离完成这项工作又近了一步,但是出现了另一个问题,我真的需要允许多个输入,例如这是我正在尝试的:

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

但我无法让它工作,roger pate 建议:

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

最佳答案

添加标题

#include <algorithm>
#include <cctype>

cout << "\nYES or NO" << endl;
string input ="";
cin >> input;
transform (input.begin(), input.end(), input.begin(),tolower);

if ( (std::string::npos != input.find( "yes" )) || (std::string::npos != input.find( "y" )) )
{
cout << "you said yes \n" ;
}
else if ( (std::string::npos != input.find( "no" ) ) || (std::string::npos != input.find( "n" ) ) )
{
cout << "you said no \n" ;
}
else
{
cout << "ERROR!!! \n" ;
}

关于c++ - 在C++中允许多种形式的 "yes"和 "no"的多种输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4106603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com