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.
Well, apparently std::string has a constructor that could be used in this case:
You can use this
std::string
constructor:so in your example:
Although the question was how to "copy a non null-terminated
unsigned char
array [...] into astd::string
", I note that in the given example that string is only used as an input tostd::cout
.In that case, of course you can avoid the string altogether and just do
which I think may solve the problem the OP was trying to solve.
std::string has a method named assign. You can use a char * and a size.
http://www.cplusplus.com/reference/string/string/assign/
This should do it:
Ew, why the cast?
Done.