在 C++ 中比较 std::string 与常量与比较 char 数组与常量
我正在尝试进行一些文本冒险来掌握 C++。
cin >> keyboard1;
if ((keyboard1 == "inv")inventory(inv);
如果 Keyboard1 是字符串,则这将起作用,但如果它是字符数组,则不起作用,这是因为我没有在常量末尾包含 null 吗?
I am trying to make a little text adventure to get a handle on C++.
cin >> keyboard1;
if ((keyboard1 == "inv")inventory(inv);
This will work if keyboard1 is a string, but won't if it's a char array, is this because I haven't included the null at the end of the constant?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
假设您的代码如下:
由于 stl 类
string
覆盖==
运算符的方式,它可以按预期工作。您不能指望下面的代码能够正常工作:
因为您正在比较 s(字符串开始的地址)和常量字符串(顺便说一句,编译器会自动以 null 结尾)。
您应该使用 strcmp 来比较“c-strings”:
这有效。
Let'say your code is the following:
This works as expected because of the way the stl class
string
overrides the==
operator.You cannot expect the following code to work instead:
because you are comparing s, which is the address where the string starts to a constant string (which, by the way, is automatically null-terminated by the compiler).
You should use strcmp to compare "c-strings":
This works.
不,它不起作用的原因是因为您将比较代表每个字符串的内存地址。请改用
strcmp
/wcscmp
。比较字符串和常量的原因是因为字符串类将定义一个相等运算符(例如bool StringClass:operator==(const char* pszString))。
No, the reason it won't work is because you will be comparing the address of the memory that represents each string. Use
strcmp
/wcscmp
instead.The reason why comparing a string and a constant work is because the string class will have an equality operator defined (e.g.
bool StringClass:operator==(const char* pszString)
).如果
keyboard1
是一个 char 数组,则if (keyboard1 == "inv")
正在执行简单的指针比较(两者都变为char*
) 。当
keyboard1
是一个字符串时,如果存在,则可以调用operator==(cosnt string&, const char*)
,否则,如果字符串有非显式的构造函数string(const char *s)
,常量"inv"
将隐式转换为字符串对象,并且operator==(const string&,const string&)
应用。If
keyboard1
is a char array, thenif (keyboard1 == "inv")
is performing a simple pointer comparison (both becomechar*
).When
keyboard1
is a string, it can call anoperator==(cosnt string&, const char*)
if one exists, otherwise, if the string has the non-explicit constructorstring(const char *s)
, the constant"inv"
would be implicitly converted to a string object, andoperator==(const string&,const string&)
applied.