如何比较字符串形式的临时变量

How to compare the temporary variables in the form of string?

本文关键字:变量 字符串 何比较 比较      更新时间:2023-10-16

我想知道为什么两个结果不同?

代码为:

string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;

输出为:

1 0

C++中的文字字符串实际上是常量字符的数组。与任何其他数组一样,它们衰减为指向其第一个元素的指针。

使用 "35">"255" 您可以比较指针,而不是字符串本身的内容。

要比较文字字符串,您需要使用 std::strcmp .但请注意,它不返回布尔值。

您当前所做的大致相当于

char const* a = "35";
char const* b = "255";
std::cout << (&a[0] > &b[0]) << 'n';  // Print the result of comparing the *pointers*

使用 s1>s2 调用 std::stringoperator> 函数。表达式 s1 > s2 等效于 s1.operator>(s2)

因为"35"和"255"不是std::string,所以它是一个const char[](即字符数组(。当您声明 s1 和 s2 时,const char[] 将转换为 std::string,因为 s1 和 s2 的类型是 std::string,但它不会自动执行此操作。

运行cout << (s1>s2) << " " << (string("35") > string("255")) << endl应按预期工作。

您可以使用 strcmp((,它根据字符串的比较返回正值或负值。
在这里查看手册:strcmp((

请注意,它采用常量字符*而不是字符串作为参数。