c++ - 比较字符串时出现意外结果

标签 c++ string compare

我正在比较这两个字符串:"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 and q 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 of p<q, p>q, p<=q, and p>=q are unspecified.

然而,您可以通过 std::less 以明确定义的方式比较此类指针。和家人,因为

C++11 20.8.5/8(比较):

For templates greater, less, greater_equal, and less_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/

相关文章:

c# 嵌套 for 循环检查比较列表中的每个元素返回奇数结果

c++ - 对于大小为 4096 的缓冲区,最快的校验和算法是什么?

php - 更新一个 MySQL 表上的行,其中具有匹配列的行存在于另一个表上?

c++ - 西里尔文输入输出,c++

c++ - 从 C++ 文件中获取输入?

c++ - 为什么 auto 关键字不能与指向函数的指针的初始化列表一起使用?

string - Awk - 将后续行的长度写入行

c++ - 为什么快速排序会引发异常 “write access violation”

java - 欧元符号 JNA 转换问题

c - 从 C 中的 char 数组中修剪空格