1

#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”语句,即使我输入的是或否或无效的答案,仍然会继续 if 语句。(无论我放什么,它仍然会在 if 语句中显示消息)。

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

我知道这是一个简单的修复,但我不完全确定是什么。我有点菜鸟。此外,这可能是也可能不是做我想做的最有效的方法,但这主要是为了练习。

4

3 回答 3

2

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

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

于 2013-07-03T06:42:56.920 回答
1
if (questionThreeAnswer != "yes" and questionThreeAnswer != "no")
于 2013-07-03T06:42:22.443 回答
1

您正在检查的内容相当于以下内容

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

或者在更传统的 C++ 中

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

你想要的是

if ( questionThreeAnswer != "yes" && questionThreeAnswer != "no" )
于 2013-07-03T06:42:53.920 回答