Sivabushan
Sivabushan

Reputation: 71

comparision of strings with numbers, how does it work

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

Answers (1)

Baum mit Augen
Baum mit Augen

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

Related Questions