C++ if 使用字符串的语句不能按预期工作

2021-12-12 00:00:00 string if-statement c++

我已经搜索过此错误,但似乎没有人遇到与我相同的问题.我正在尝试用 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!
";

            double damage = return_level(xp) * 1.2;

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

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

我一直收到抱歉,我没听懂"的消息;

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 .(在 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).

相关文章