2017-08-21 47 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