C++ if statements using strings not working as intended(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!
";
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
).
这篇关于C++ if 使用字符串的语句不能按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ if 使用字符串的语句不能按预期工作


基础教程推荐
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 从 std::cin 读取密码 2021-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 管理共享内存应该分配多少内存?(助推) 2022-12-07