b) std::cout<

Comparing strings with numbers, how it works

string a = "10";
string b = "20";
if(a>b)
  std::cout<<a;
else
  std::cout<<b;

The above code gives me the correct result, but I don’t know how? Can someone please explain to me how in this case strings are compared with numbers.

+4
source share
1 answer

It works the same as any string comparison:

The two lines are compared lexicographically, and since the character '2'comes after the character '1', we have "20" > "10".

Take another example, taken from the comments: Given "100"and "99", we compare their first characters, see what '9'appears after '1', and therefore we get "99" > "100".

+8
source

Source: https://habr.com/ru/post/1615403/


All Articles