3

发布了一个关于如何使用 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;
}
4

4 回答 4

2

添加标题

#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" ; 
}
于 2010-11-05T15:11:32.100 回答
0

在大多数语言中,简单的方法是在比较之前将字符串大写。

不幸的是,在标准 C++ 中,大写更复杂。它必须非常抵制任何不能在每个可以想象的情况下完美运行的新功能。大写是一个本质上的特性——在不同的国家是不同的,有时甚至是上下文敏感的——不能在所有可以想象的情况下完美地工作。

除此之外,C 库的大写函数有点难以正确使用。

Dang,我会在这里给你一个合理的大写函数,但没有时间。:-( 搜索关于大写的早期问题。这应该有效!:-)

干杯,

于 2010-11-05T14:13:51.073 回答
0

更简单的方法是预先转换大小写。假设用户将其输入限制为有效字符串之一(是/否)。

查看Boost.String,它是类算法的集合std::string(特别是这里的案例转换例程)。

它适用于 ASCII 字符,但既然我们谈论的std::string是应该没问题,你不打算处理日语或阿拉伯语,是吗 :) ?

于 2010-11-05T14:25:49.013 回答
0

不如只检查字符串的前两个字符,看看它们是 n N 还是 Y y?

我已经有一段时间没有使用 C++ 字符串了,但是有几个函数看起来很有趣。看看这个网站。例如,您可以获取字符串的长度。然后你可以使用我喜欢的函数在零、一和两个位置 获取 字符。之后查看第一个字符是否为 Y,y,N,n。如果您想更加确定用户没有输入废话,您可以继续(如果第一个字母是 N 或 n 检查 O 或 o 中的第二个等等),但我认为这对于简单的决定来说已经足够了.

于 2010-11-05T14:55:11.353 回答