0

How come when comparing strings...

string e = "11" 
string f = "102" 
string s = "8" 


e > s - this statement is false 
f > s - and this is also false 

How come those statements are false? And what are the rules when comparing two strings to each other?

4
  • 6
    Those are string literals, and the comparison will end up being between const char* which is simply comparing pointer addresses, which is useless for what you're probably looking for (lexicographical sorting or maybe numerical sorting?) Commented Nov 7, 2018 at 19:52
  • 1
    std::string values are compared character by character. Imagine replacing characters '0'...'9' with characters 'a'...'j'. "bb" < "i" alphabetically, and same with "bac" < "j". Commented Nov 7, 2018 at 19:54
  • 2
    Please provide a minimal reproducible example. Details do matter, "11" > "8" is different from string("11") > string("8") Commented Nov 7, 2018 at 19:58
  • taking into account the edit, the duplicate isnt a duplicate anymore. reopened the question Commented Nov 8, 2018 at 14:17

1 Answer 1

2

Using relational operators on strings in C/C++ will simply compare the memory addresses of the strings. Obviously "11" and "8" are occupying 2 different areas of memory, so it could be false, unless the address where "11" is stored happens to be stored in an address greater than "8", but it's random.

Keep in mind that you can use string::compare, however, it's comparing the ASCII code's of the strings. Since "1" (ASCII Code 49) is less than "8" (ASCII Code 56), it will still be false. You need to use stoi to convert the string to an integer, then compare the integers.

Sign up to request clarification or add additional context in comments.

2 Comments

Good answer, but it may be worth mentioning/explaining that even if he were comparing std::string's so that it would compare the string values and not the addresses, "11" would still evaluate to less than "8".
No need engage in such blatant ASCIIism here. <g> '1' is required to be less than '8' in every character set supported by C or C++ compilers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.