If the array was null-terminated this would be pretty straight forward:
unsigned char u_array[4] = { \'a\', \'s\', \'d\', \'\\0\' };
std::string str
You can use this std::string
constructor:
string ( const char * s, size_t n );
so in your example:
std::string str(u_array, 4);
std::string
has a constructor that takes a pair of iterators and unsigned char
can be converted (in an implementation defined manner) to char
so this works. There is no need for a reinterpret_cast
.
unsigned char u_array[4] = { 'a', 's', 'd', 'f' };
#include <string>
#include <iostream>
#include <ostream>
int main()
{
std::string str( u_array, u_array + sizeof u_array / sizeof u_array[0] );
std::cout << str << std::endl;
return 0;
}
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:
// --*-- 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;
}
Although the question was how to "copy a non null-terminated unsigned char
array [...] into a std::string
", I note that in the given example that string is only used as an input to std::cout
.
In that case, of course you can avoid the string altogether and just do
std::cout.write(u_array, sizeof u_array);
std::cout << std::endl;
which I think may solve the problem the OP was trying to solve.
Try:
std::string str;
str.resize(4);
std::copy(u_array, u_array+4, str.begin());
std::string has a method named assign. You can use a char * and a size.
http://www.cplusplus.com/reference/string/string/assign/