C ++ if语句使用字符串无法按预期工作

问题描述:

我已经搜索了此错误,但似乎没有人遇到与我相同的问题。我正在尝试使用C ++创建一个基于文本的基本RPG游戏来学习,我希望用户能够键入他们想做的事,例如,如果他们键入 ATTACK 他们会攻击怪物,但是我的if语句:

I have searched for this error but noone seems to be having the same problem as me. I am trying to make a basic text based RPG game in C++ to learn, and I want the user to be able to type what they want to do, for example if they type ATTACK they will attack the monster, but my if statement:

if((current_move == "ATTACK") || (current_move == "attack"))

返回错误!

这是下面的完整功能:

while(monster_health > 0)
    {
        std::cin >> current_move;
        std::cout << current_move;
        if((current_move == "ATTACK") || (current_move == "attack"))
        {
            std::cout << "You attacked the monster!\n";

            double damage = return_level(xp) * 1.2;

            std::cout << "You did " << damage << " damage!\n";

            monster_health -= damage;
            if(monster_health < 0)
            {
                monster_health = 0;
                break_out = true;
            }
        }
        else if(current_move == "FLEE")
        {
            std::cout << "You ran away...\n";
            break_out = true;
        }
        else
        {
            std::cout << "Sorry, I didn't understand, what will you do? ATTACK or FLEE?\n";
        }
    }

我只是不断收到对不起,我没有理解消息。

I just keep getting "Sorry, I didn't understand" message;

请让我知道其他错误或不良做法,因为我才刚刚开始学习:)

Please let me know of any other errors or bad practises as I've only just started learning :)

current_move 是什么类型?如果它是 char * (或 char [] ),则您是在比较指针,而不是字符串。最好使用 std :: string current_move ,那么与 == 的比较将很直观。

What's the type of current_move? If it's char* (or char[]), you are comparing pointers, not strings. Better use std::string for current_move, then the comparison with == will work intuitively.

您需要添加 #include< string> 。 (在MSVC中,字符串的某些部分也可以不这样做,但这是非标准的,并且会导致错误,例如,将字符串传递给 cout 时)。

You need to add #include <string>. (In MSVC certain parts of strings also work without that, but it's nonstandard and leads to errors e.g. when passing strings to cout).