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.
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With