如果语句问题嵌套 - 比较运算符

时间:2016-08-26 14:05:29

标签: c++ dev-c++

(使用dev c ++)由于我对c ++很陌生,所以我决定制作基本的文本RPG游戏。我已多次调试该程序,它没有任何结果。每次我测试程序,并且,假设我想攻击旅行者,它打印TEST(我暂时放在那里,直到我能解决问题)。如果我用if(攻击==“对话”||“攻击”)切换if(攻击==“对话”||“对话”),那么我想和旅行者交谈,打印出“你向前冲去谋杀”旅行者发现他没有武装!“所有帮助将不胜感激。

#include <iostream>
#include <string>


using namespace std;

int main() {
    string dir, attack, trade;
    string inventory[] = {"Food", "Sword", "Armor"};
    cout << "Do you go left, right or forward?" << endl;
    cin >> dir;
    if(dir=="left"||"Left") {
        cout << "You decide to go left" << endl;
        cout << "On the way you meet a traveller, do you attack or talk?" << endl;
        cin >> attack;
       if(attack=="talk"||"Talk") {
             cout << "TEST" << endl;
             }
       else if(attack=="attack"||"Attack") {
             cout << "You rush forward and murder the traveller to find he was un-armed!\a" << endl;
             }
       else  {
             cout << "test" << endl;
             }

     }
    else if(dir=="Right"||"Right") {
        cout << "You decide to go right" << endl;
        }
    else {
         cout << "You decide to go forward" << endl;
         }
    system("PAUSE");
    return 0;
}

2 个答案:

答案 0 :(得分:3)

您正在使用||运算符,例如if(dir=="Right"||"Right")

这是错误的用法,因为它总是将第二部分"Right"评估为true。将 ALL 更改为此例程:

if(dir=="Right"|| dir=="Right")

但是,这里两个语句都是相同的,因为“Right”与“Right”相同。检查你的逻辑,你的意思是dir == "Right" || dir == "right"

在解决我提到的问题之后,这是代码的干净副本:

int main() 
{
    string dir, attack, trade;
    string inventory[] = { "Food", "Sword", "Armor" };

    cout << "Do you go left, right or forward?" << endl;
    cin >> dir;

    if (dir == "left" || dir == "Left")
    {
        cout << "You decide to go left" << endl;
        cout << "On the way you meet a traveller, do you attack or talk?" << endl;
        cin >> attack;

        if (attack == "talk" || attack == "Talk")
            cout << "TEST" << endl;
        else if (attack == "attack" || attack == "Attack") 
                    cout << "You rush forward and murder the traveller to find he was un-armed!\a" << endl;
                else 
                    cout << "test" << endl;
    }
    else if (dir == "Right" || dir == "right") 
                cout << "You decide to go right" << endl;
            else 
                cout << "You decide to go forward" << endl;

    system("PAUSE");
    return 0;
}

答案 1 :(得分:1)

除了songyuanyao&firstStep的答案之外,还有一个解释:

if(dir == "left" || "Left")

相当于

if((dir == "left") || ("Left"))

再次等同于

if((dir == "left") || ("Left" != 0))

作为字符串文字&#34;左&#34;内存中的地址不等于0 ......

旁注:&#34;左&#34;为此,我甚至没有转换为std :: string。

相关问题