std::string
is perfectly capable of storing nulls. However, you have to be wary, as const char*
is not, and you very briefly construct a const char*
, from which you create the std::string
.
std::string a("\x00");
This creates a constant C string containing only the null character, followed by a null terminator. But C strings don't know how long they are; so the string thinks it runs until the first null terminator, which is the first character. Hence, a zero-length string is created.
std::string b("");
b.push_back('\0');
std::string
is null-clean. Characters (\0
) can be the zero byte freely as well. So, here, there is nothing stopping us from correctly reading the data structure. The length of b
will be 1
.
In general, you need to avoid constructing C strings containing null characters. If you read the input from a file directly into std::string
or make sure to push the characters one at a time, you can get the result you want. If you really need a constant string with null characters, consider using some other sentinel character instead of \0
and then (if you really need it) replace those characters with '\0'
after loading into std::string
.
strlen("\x00");
for the same result. – Couchantstrlen(3)
is not a C++ function. It's a C legacy function, that does not know about c++string
type. You cannot use it withstring
s but by converting thestring
to a legacy Cchar *
string. That way,strlen(3)
doesn't know about array sizes, it only searches for the\0
char and returns the difference between the pointer passed to it and the place where it found the null char. – Fatma