Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistency between C++ std::string::compare() and the operator on string

Given the below piece of C++ code

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

The output of this code is

0
1
1

Which means "100" < "035" by the operator but "100" > "035" by the compare function. Is there any known implementation differences of these two?

P.S. "100" > "035" definitely makes more sense.

like image 590
Keerthana S Avatar asked Jun 28 '26 05:06

Keerthana S


1 Answers

C-String literals (such as "100") compare themselves as pointer.

std::string comparison compare content lexicography.

If you want consistent results:

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"s is "equivalent" to std::string("100").

like image 122
Jarod42 Avatar answered Jun 29 '26 19:06

Jarod42