【问题标题】:Inconsistency between C++ std::string::compare() and the operator on stringC++ std::string::compare() 与字符串上的运算符之间的不一致
【发布时间】:2020-04-19 05:55:56
【问题描述】:

鉴于以下 C++ 代码

cout<<("100">"035")<<"\n";
cout<<("100"<"035")<<"\n";
string str = "100";
cout<<str.compare("035");

这段代码的输出是

0
1
1

运算符表示“100”“035”。这两者有什么已知的实现差异吗?

附: "100" > "035" 肯定更有意义。

【问题讨论】:

    标签: c++ string compare


    【解决方案1】:

    C-String 字面量(例如"100")将它们自己作为指针进行比较。

    std::string比较比较内容词典。

    如果您想要一致的结果:

    using namespace std::string_literals;
    std::cout << ("100"s > "035"s)<<"\n";
    std::cout << ("100"s < "035"s)<<"\n";
    std::string str = "100"s;
    std::cout << str.compare("035");
    

    "100"sstd::string("100")“等效”。

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2022-12-01
      • 2017-08-28
      • 1970-01-01
      • 2017-06-06
      • 1970-01-01
      • 2019-08-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多