C++ why do capital letters effect comparison with strings (sorting names)

Viewed 146

I am fairly new to C++, working through Bjarne Stroustrup's "Programming and Practices using C++, 2nd Edition".

I am doing an exercise where you sort three names. I did this using the tools provided up to this point, so as not to jump ahead of the book. The method is to just use greater-than and less-than in an if statement.

I tried testing this with many inputs, and found something odd: When I use capital letters, it doesn't always sort properly. Can anyone explain why?

string name1, name2, name3;
cout << "Enter three names : \n";
cin >> name1 >> name2 >> name3;
if (name1 > name2)
{
    string temp;
    temp = name2;
    name2 = name1;
    name1 = temp;
}
if (name2 > name3)
{
    string temp;
    temp = name3;
    name3 = name2;
    name2 = temp;
}
if (name1 > name2)
{
    string temp;
    temp = name2;
    name2 = name1;
    name1 = temp;
}
cout << "In alphabetical order : \n" << name1 << '\n' << name2 << '\n' << name3;

The output of this test:

image

1 Answers

From an EE perspective, consider that strings in C++ (or C for that matter) are simply binary-encoded data within the machine.

Each character (letter, number, symbol) - is assigned an ASCII numeric value so the computer can interpret what character you are referencing.

The thing to understand here is that lower case (e.g. 'a') and uppercase letters (e.g. 'A') have different numeric values. Therefore, when all the characters in a string are compared, strings with different capitalisation result in different numeric values, hence the behaviour you are seeing.

Remember, to a human - you are comparing a string. To the machine, it creates a numberic representation of the string and compares it that way.

EDIT: Here is the reference for the 'compare' function, that the < and >

Related