C++:比较运算符>和字符串字面值的意外结果

3

C++中的std::string类实现了比较运算符。以下代码输出AAA

#include <iostream>
using namespace std;
int main() {

    if("9">"111")
        cout << "AAA";
    else 
        cout << "not AAA";

    return 0;
}

这段代码打印出 not AAA
#include <iostream>
using namespace std;
int main() {

    if("9">"111")
        cout << "AAA";
    else 
        cout << "not AAA";

    if("99">"990")
        cout << "BBB";

    return 0;
}

为什么会这样?

9
你的代码中哪里使用了 std::string"blah" 不是一个 std::string - NathanOliver
1
区分 std::string 和 C 字符串。 - user2486888
1
你正在比较 const char* 值,而不是 std::string - user0042
3
我不确定为什么这个被踩了。这是一个非常自然的错误,问题本身也清晰易懂并包含可重现的例子。这甚至对 Stack Overflow 来说都有些恶意。 - Nir Friedman
@NirFriedman 不是说这是使用的原因,我也没有投票,但缺乏研究是一个有效的理由,弄清楚“blah”是什么,是OP应该能够查找的内容。 - NathanOliver
要使用std :: string,你需要在程序的某个地方声明、转换或以某种方式指定std :: string。C++不会自动将字符串文字转换为std :: string对象。 - PaulMcKenzie
1个回答

5

您正在比较位于静态持续存储器上的字符串文字的地址,这具有未指定的行为。

像这样使用 std :: string

#include <iostream>
using namespace std;
int main() {

    if(std::string("9") > std::string("111"))
        cout << "AAA";
    else 
        cout << "not AAA";

    return 0;
}

编辑

使用using namespace std::literals;,就可以使用"9"和"111"。

谢谢@sp2danny


5
没有"未定义行为"。 - user0042
6
比较两个指针,如果它们不指向同一个数组的元素,则具有未定义行为。 - StoryTeller - Unslander Monica
5
@StoryTeller,实际上,它似乎只是未指明的。 - Nir Friedman
2
@StoryTeller 没有异议,但答案应该是正确的,而未定义和未指定是相当不同的。Filip,您是否考虑进行更正? - Nir Friedman
2
通过使用 using namespace std::literals;,可以使用 "9"s"111"s" - sp2danny
显示剩余10条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接