C++ 如何只接受;“是”;或;";在用户';以C++;?

C++ 如何只接受;“是”;或;";在用户';以C++;?,c++,input,cin,C++,Input,Cin,我制定的代码是: while (*user is not closing the program*) { cout << "Make a decision? (y/n) " << endl; cin >> userAnswer; ... if (UsersAnswer != 'y' || UsersAnswer != 'n') cout << "You may only type y or n.";

我制定的代码是:

while (*user is not closing the program*)
{
    cout << "Make a decision? (y/n) " << endl;
    cin >> userAnswer;
    ...
    if (UsersAnswer != 'y' || UsersAnswer != 'n')
        cout << "You may only type y or n.";
}
while(*用户未关闭程序*)
{
不能回答;
...
if(UsersAnswer!=“y”| UsersAnswer!=“n”)

你知道当你在做什么吗

do
{
    std::cout << "Yes or no yadda yadda yadda" << std::endl;
    std::cin >> userAnswer;
}
while( !std::cin.fail() && userAnswer!='y' && userAnswer!='n' );
do
{
std::coutuseranswer;
}
而(!std::cin.fail()&&userAnswer!='y'&&userAnswer!='n');
但是,当我输入诸如“你好”之类的句子或单词时,它会破坏代码(无限次地输出“做出决定”)


发生这种情况的原因是因为您输入了
hello
,并且您的代码逐字符读取,例如
'h'
'e'
'l'
,等等。对于每个字符,它都会检查它是
'y'
还是
'n'
,并且每次它都按照您的代码指示执行:
循环时不能使用
serAnswer
come from?@wkl该段代码在一个while循环中。请提供一个。当您尝试从与流中的数据不匹配的流中读取数据时,该流进入错误状态。在错误状态为
clear
ed之前,be流无法写入或读取。因为您没有检查以确保
cin>>userAnsw呃;
没有失败,并且清除了错误,循环尝试读取,失败,一个永远循环。很好,但是当我输入多个字符时,它将连续打印
“是或否yadda yadda yadda”
,直到输入变为空。
#include <iostream>
#include <limits>

using namespace std;

int main()
{
    char userAnswer;
    while (1 /*user is not closing the program*/)
    {
        cout << "Make a decision? (y/n) " << endl;
        cin >> userAnswer;
        cout << "entered: '" << userAnswer << "'\n";
        userAnswer = tolower(userAnswer);
        if (userAnswer == 'y' || userAnswer == 'n')
            break;

        cout << "You may only type 'y' or 'n'.\n";
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}