2017-08-21 52 views
3

在C++中,std :: string类实现了comparison operators。 下面的代码打印AAAC++:比较运算符>和字符串文字的意外结果

#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-string。 –

+1

您正在比较'const char *'值,而不是'std :: string'。 – user0042

回答

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” S和 “111” 秒。

谢谢你@ sp2danny

+5

没有_undefined behavior_。 – user0042

+1

请注意,仅将其中一个设置为“std :: string”即可。 –

+6

@ user0042 - 比较*不指向同一数组元素的两个指针具有未定义的行为。 – StoryTeller