Reputation: 85
I have a strange with string with 0x0, can someone help me?
string a = funxx(); // funxx is a external func from Crypto++ libary
string b = "test"
if I print out the content of a and b, they both display as "test"
a.size() is: 5
b.size() is: 4
a.length() is: 5
b.length() is: 4
for( int i = 0; i < a.size(); i++ ) {
cout << "0x" << hex << (0xFF & static_cast<byte>(a[i])) << " ";
}
print out: 0x74 0x65 0x73 0x74 0x0
for( int i = 0; i < b.size(); i++ ) {
cout << "0x" << hex << (0xFF & static_cast<byte>(b[i])) << " ";
}
print out: 0x74 0x65 0x73 0x74
My question is, why a.length()
and a.size()
return 5
instead of 4
, and how to make a
and b
are equal?
Summary:
Thanks for lots of replies. I think the problem is clear for me now. The external func
from Crypto++ libary return an extra null character in the string, and in string, the length is tracked separately.
What I need to do is std::string(a.c_str())
Upvotes: 3
Views: 921
Reputation: 308206
A simple way to remove a trailing null from a std::string
:
if (!str.empty() && *str.rbegin() == 0)
str.resize(str.size() - 1);
Upvotes: 1