c_str() returning a const char*, I would assume the following code to print "equal", but it doesn't.
Could someone explain to me where am I wrong ?
string xx = "hello";
const char* same = "hello";
const char* buf = xx.c_str();
if (buf == same)
{
cout << "equal" << endl;
}
I would assume the following code to print "equal"
That's a wrong assumption. std::string
copies the literal data to its internal buffer, so the pointers will differ.
In case you wanted to compare the data instead of pointers, don't use c_str()
at all and compare the const char*
to the string
directly - the overloaded comparison operator will do what you expect it to.
operator==
for const char*
does not do a string comparison, it directly compares the pointers. The buffer used by xx
is not the same as the same
pointer, so they are not equal.
To do string comparison with a std::string
and a const char*
you can just use the operator provided by std::string
:
if (xx == same)
{
cout << "equal" << endl;
}
Operator ==
for char*
pointers compares the pointers themselves, not the strings they point to.
If you want to second-guess std::string, you need to use comparison routines, like following:
if (strncmp(buf, same, xx.size())
...
buf == same
is not comparing the strings but the address of the pointers. Since they are two different variables they will have two different address that will not be equal. If you need the compare char*
s or const char*
s then you can use std::strcmp
You are comparing the values of two pointers, which can never be equal. same
points to read-only memory, and the pointer returned by c_str
is the current data buffer of the std::string
object with a null terminator guaranteed to be appended.
You could write xx == same
: this is because std::string
overloads ==
with the appropriate data types. Alternatively, and perhaps less elegantly, you could use std::strcmp
on the two pointers.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.