Reputation: 71
string a = "10";
string b = "20";
if(a>b)
std::cout<<a;
else
std::cout<<b;
The above code gives me correct output, but I don't know how? Can someone please explain me how strings with numbers are compared in this case.
Upvotes: 4
Views: 119
Reputation: 50053
It works just like any string comparison:
The two strings are compared lexicographically, and since the character '2'
comes after the character '1'
, we have "20" > "10"
.
Let's do another example, taken from the comments: Given "100"
and "99"
, we compare their first characters, see that '9'
comes after '1'
, and so we get "99" > "100"
.
Upvotes: 8