C ++ - if语句检查字符串不正确

时间:2013-07-03 06:39:12

标签: c++ if-statement

#include <iostream>
#include <string>
using namespace std;

string questionOneAnswer;
string questionTwoAnswer;
string questionThreeAnswer;


class quizAshton{
    public:
        string question1(){
            cout << "What is your favorite food?" << endl;
            cin >> questionOneAnswer;
            return questionOneAnswer;
        }
        string question2(){
            cout << "What is the name of someone you hate?" << endl;
            cin >> questionTwoAnswer;
            return questionTwoAnswer;
        }
        string question3(){
            cout << "Hi! (yes or no)" << endl;
            cin >> questionThreeAnswer;
            return questionThreeAnswer;
        }

};

int main()
{
    quizAshton ashtonAnswers;

    ashtonAnswers.question1();
    ashtonAnswers.question2();
    ashtonAnswers.question3();

    if (questionThreeAnswer!= "yes" or "no"){
    cout << "I asked for a yes or no! You betrayed me!" << endl;
    return 0;
    }

    cout << "APPARENTLY your favorite food is " << questionOneAnswer << "... I guess I wouldn't really believe that unless it was eaten by " << questionTwoAnswer << "and is the cat ready...: " << questionThreeAnswer << endl;

    return 0;
}

#include <iostream> #include <string> using namespace std; string questionOneAnswer; string questionTwoAnswer; string questionThreeAnswer; class quizAshton{ public: string question1(){ cout << "What is your favorite food?" << endl; cin >> questionOneAnswer; return questionOneAnswer; } string question2(){ cout << "What is the name of someone you hate?" << endl; cin >> questionTwoAnswer; return questionTwoAnswer; } string question3(){ cout << "Hi! (yes or no)" << endl; cin >> questionThreeAnswer; return questionThreeAnswer; } }; int main() { quizAshton ashtonAnswers; ashtonAnswers.question1(); ashtonAnswers.question2(); ashtonAnswers.question3(); if (questionThreeAnswer!= "yes" or "no"){ cout << "I asked for a yes or no! You betrayed me!" << endl; return 0; } cout << "APPARENTLY your favorite food is " << questionOneAnswer << "... I guess I wouldn't really believe that unless it was eaten by " << questionTwoAnswer << "and is the cat ready...: " << questionThreeAnswer << endl; return 0; }

在main下的“if”语句,即使我输入yes或no或无效的答案,仍将继续if语句。 (无论我放什么,它仍会在if语句中显示消息)。

我知道这是一个简单的修复,但我不完全确定是什么。我有点像诺贝尔。此外,这可能是也可能不是我正在尝试做的最有效的方式,但这主要是为了练习。

3 个答案:

答案 0 :(得分:2)

if (questionThreeAnswer!= "yes" or "no")
应该是 if ((questionThreeAnswer != "yes") && (questionThreeAnswer != "no"))

另外我建议你不要忘记输入中的字母大小写,在std库中应该有类似equalsIgnoreCase()toUpper()的内容来检查忽略大小写的答案。

答案 1 :(得分:1)

if (questionThreeAnswer != "yes" and questionThreeAnswer != "no")

答案 2 :(得分:1)

您检查的内容与以下内容相同

if ( (questionThreeAnswer!= "yes") or ("no") )

或更传统的c ++

if ( (questionThreeAnswer!= "yes") || ("no") )

你想要的是

if ( questionThreeAnswer != "yes" && questionThreeAnswer != "no" )