I am very new to C++ and i was wondering if std::string str(array.begin(), array.end())
is adding a null character on its own at the end of the string? I looked up this reference but i could not figure it out. I appreciate your answers!
Edit:
I am using C++11 and I have an boost::array<u_int8_t>
of uknown size. My goal ist to print it afterwards with str.c_str()
because %s
is expecting a char*
.
str = std::string(arr.begin(),arr.end());
ROS_INFO("Got response: \n %s", str.c_str());
The C++ standard specifies that c_str()
returns a null-terminated string (the contents of the string followed by a '\0'
). Depending on C++ standard version, you may or may not be guaranteed that str[str.size()]
also gives you a '\0'
.
That's the only thing that the C++ standard specifies. Whether the '\0'
is originally added by its constructor, or not, including this specific constructor: this is unspecified.
However, since you are guaranteed to get that all-important '\0'
when you go look for it, this is a moot point. It will be there.
Since C++11 std::string
must contain a terminating null character. However, a null character in a std::string
does not necessarily terminate the std::string
.
I hope it gets more clear with the following example:
#include <string>
#include <iostream>
int main() {
std::string x{"Hello World"};
std::cout << x.c_str() << "\n";
x[5] = '\0';
std::cout << x << "\n";
std::cout << x.c_str();
}
prints:
Hello World
HelloWorld
Hello
We can get a null-terminated c-string via c_str
to get the expected output. The <<
overload knows where to stop because there is a null-terminator. Though after adding a \0
in the middle of the std::string
we can still print the whole string with the <<
overload for std::string
.
Calling c_str
again, will again return a pointer to a c-string with 10 characters + the terminating \0
, but this time the <<
overload for char*
stops when it encounters the first \0
, because thats what indicates the end of a c-string.
TL;DR: Unless you need to get a c-string from the std::string
you need not worry about adding the null-terminator. std::string
does that for you. On the other hand you should be aware that std::string
can contain null characters also in the middle not only at their end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With