Alex Rivera | Logout

Copying non null-terminated unsigned char array to std::string

Asked 2011-01-14T13:40:23.630
56

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.

Edit
Report

2 Answers

8

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:

// --*-- C++ --*--

#include <string>
#include <iostream>


int
main ()
{
    unsigned char u_array[4] = { 'a', 's', 'd', 'f' };
    std::string str (reinterpret_cast<const char *> (u_array),
                     sizeof (u_array) / sizeof (u_array[0]));
    std::cout << "-> " << str << std::endl;
}
answered 2011-01-14T13:47:54.053
4

std::string has a method named assign. You can use a char * and a size.

http://www.cplusplus.com/reference/string/string/assign/

answered 2011-01-14T13:45:04.677

Your Answer