Comparative values of strings?

So I've come across some strange results and I am looking for an explanation...


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <string>
#include <vector>

using namespace std;



int main()
{
    vector<string> strings;
    strings.push_back("b");
    strings.push_back("a");

    cout << "Is " << strings[0] << " > " <<strings[1] << "?:    ";
    if (strings[0] > strings[1])
    {
        cout << "YES!\n";   //Outputs yes, makes sense because ascii value od b is greater?
    }   else cout << "NO!\n";


    strings[0] = "a";
    strings[1] = "b";
    cout << "Is " << strings[0] << " > " <<strings[1] << "?:    ";
    if (strings[0] > strings[1])
    {
        cout << "YES!\n";   //Outputs no, makes sense because ascii value of b is greater?
    }   else cout << "NO!\n";

    strings[0] = "mon";
    strings[1] = "mom";
    cout << "Is " << strings[0] << " > " <<strings[1] << "?:    ";
    if (strings[0] > strings[1])
    {
        cout << "YES!\n";   //Outputs yes, makes sense because ascii value of n is greater?
    }   else cout << "NO!\n";

    strings[0] = "mom";
    strings[1] = "mon";
    cout << "Is " << strings[0] << " > " <<strings[1] << "?:    ";
    if (strings[0] > strings[1])
    {
        cout << "YES!\n";   //Outputs no, makes sense because ascii value of n is greater?
    }   else cout << "NO!\n";


    //Here is my problem:

    strings[0] = "momn";
    strings[1] = "mnmo";
    cout << "Is " << strings[0] << " > " <<strings[1] << "?:    ";
    if (strings[0] > strings[1])
    {
        cout << "YES!\n";   //Outputs yes, DOES NOT MAKE SENSE. Shouldn't they be the same value?
    }   else cout << "NO!\n";

    strings[0] = "Test";
    strings[1] = "hi";
    cout << "Is " << strings[0] << " > " <<strings[1] << "?:    ";
    if (strings[0] > strings[1])
    {
        cout << "YES!\n";   //Outputs no, DOES NOT MAKE SENSE. Shouldn;t "Test" be greater?
    }   else cout << "NO!\n";
}


I need to know why one string is greater than another, thanks for your help
Hi,

With "momn" vs "mnmo" , "mo" is greater than "mn" when looking at the ASCII chart, so the function returns true.

With "Test" vs "hi" , the same: "T" is less than "h" looking at the ASCII chart.

It works this way because char is really just a small int. It might work differently if one had a different locale, or a different character set.

http://en.cppreference.com/w/cpp/language/ascii
Topic archived. No new replies allowed.