Why this code

if ("j" > "J")

return false, but this:

string a = "j";
string b = "J";

if (a > b)

return true? Which is the correct answer and how can i fix it?

有帮助吗?

解决方案

That is happenig because "j" and "J" are const char []. For exampe "j" is array of chars that c[0]='j' and c[1]='\0'. In C and C++ you can't compare two arrays. it is better to use

strcmp("j","J");

witch is in

When you type

string a="j"

you run constructor in class string. But in class string you have overloaded operator< to compare two strings.

其他提示

You can use single quotes to compare symbols: if ('j' > 'J')

This is because "j" and "J" are string literals, which are compared as const char pointers. The result of the comparison is therefore arbitrary, because the placement of literals in memory is implementation defined.

On the other hand, when you make std::string objects from these string literals, the < operator (along with other comparison operators) is routed to an override provided by the std::string class. This override does a lexicographic comparison of the strings, as opposed to comparing pointer values, so the results of comparison look correct.

You can try

if ("J" < "j")

and may be get a different result.

In fact "J" and "j" are constant C strings and may be placed on .data or .text sections which is determined by the output binary file format. So when you compare them, you are comparing their address in the memory.

But std::string is a C++ class which overloads the > operator, so it's not address/pointer comparing but content comparing.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top