我正在比较这两个字符串:"code"
和 "test"
当我在 Visual Studio 中键入此内容时:
cout<<("t"<"c")<<endl;
cout<<("c"<"t")<<endl;
cout<<("code"<"test")<<endl;
cout<<("test"<"cose")<<endl;
结果是:
1
0
1
1
这没有意义,当我尝试在 ideone.com 上尝试时,结果变成:
0
1
1
1
这里出了什么问题?
最佳答案
您比较的是指针值,而不是字符串(注意:"cose"
与 "code"
是不同的文字,¹保证给出不同的指针)。
使用 std::string
来自 <string>
header 以获得有意义的字符串操作。
然后你也可以使用像"code"s
这样的文字.
#include <iostream>
#include <string>
using namespace std;
auto main() -> int
{
cout << boolalpha;
cout << ("t"s < "c"s) << endl;
cout << ("c"s < "t"s) << endl;
cout << ("code"s < "test"s) << endl;
cout << ("test"s < "cose"s) << endl;
}
正式问题中的代码,
cout<<("t"<"c")<<endl;
cout<<("c"<"t")<<endl;
cout<<("code"<"test")<<endl;
cout<<("test"<"cose")<<endl;
... 具有实现定义的行为,因为
C++11 §5.9/2 2nd 破折号 (expr.rel):” If two pointers
p
andq
of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results ofp<q
,p>q
,p<=q
, andp>=q
are unspecified.
然而,您可以通过 std::less
以明确定义的方式比较此类指针。和家人,因为
” For templates
greater
,less
,greater_equal
, andless_equal
, the specializations for any pointer type yield a total order, even if the built-in operators<
,>
,<=
,>=
do not.
但是在第三只手上,虽然指针比较在某些情况下很有用,但您可能想要比较字符串文字。标准库提供例如strcmp
为了做到这一点。但最好使用 std::string
,如开头所述。
文字 "code"
表示一个不可变的空终止字符串 char
值。最后一个空字节总共是五个 char
值。因此类型是 char const[5]
.
作为在需要指针的上下文中使用的表达式,表示此数组的表达式(即 "code"
字面量)退化为指向第一项的指针,即 char const*
。指针。
这是数组表达式到指针的常见衰减,但在 C++03 和更早版本中,还有一条特殊的字面量规则允许衰减到 char*
。 (没有const
)。
<支持>
注意事项:
¹ 两个相同的字符串文字可以提供不同的指针或相同的指针,具体取决于所使用的编译器和选项。
关于c++ - 比较字符串时出现意外结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39545246/