Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is std::string str(array.begin(), array.end()) adding the null character on its own?

Tags:

c++

string

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()); 
like image 623
mab0189 Avatar asked Dec 04 '22 17:12

mab0189


2 Answers

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.

like image 139
Sam Varshavchik Avatar answered Jan 10 '23 19:01

Sam Varshavchik


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.

like image 35
463035818_is_not_a_number Avatar answered Jan 10 '23 20:01

463035818_is_not_a_number