If the array was null-terminated this would be pretty straight forward:
unsigned char u_array[4] = { 'a', 's', 'd', '\0' };
std::string str = reinterpret_cast<char*>(u_array);
std::cout << "-> " << str << std::endl;
However, I wonder what is the most appropriate way to copy a non null-terminated unsigned char array, like the following:
unsigned char u_array[4] = { 'a', 's', 'd', 'f' };
into a std::string
.
Is there any way to do it without iterating over the unsigned char array?
Thank you all.
std::string
has a constructor that takes a pair of iterators andunsigned char
can be converted (in an implementation defined manner) tochar
so this works. There is no need for areinterpret_cast
.Of course an "array size" template function is more robust than the
sizeof
calculation.When constructing a string without specifying its size, constructor will iterate over a a character array and look for null-terminator, which is
'\0'
character. If you don't have that character, you have to specify length explicitly, for example:Try:
There is a still a problem when the string itself contains a null character and you try to subsequently print the string:
However....
Its times like these when you just want to ditch cuteness and use bare C.
You can create a character pointer pointing to the first character, and another pointing to one-past-the-last, and construct using those two pointers as iterators. Thus:
std::string has a constructor taking an array of char and a length.