Copying non null-terminated unsigned char array to

2019-01-13 17:48发布

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.

12条回答
smile是对你的礼貌
2楼-- · 2019-01-13 18:21

Well, apparently std::string has a constructor that could be used in this case:

std::string str(reinterpret_cast<char*>(u_array), 4);
查看更多
疯言疯语
3楼-- · 2019-01-13 18:23

You can use this std::string constructor:

string ( const char * s, size_t n );

so in your example:

std::string str(u_array, 4);
查看更多
走好不送
4楼-- · 2019-01-13 18:27

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.

查看更多
贪生不怕死
5楼-- · 2019-01-13 18:29

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

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

查看更多
Animai°情兽
6楼-- · 2019-01-13 18:29

This should do it:

std::string s(u_array, u_array+sizeof(u_array)/sizeof(u_array[0]));
查看更多
\"骚年 ilove
7楼-- · 2019-01-13 18:29

Ew, why the cast?

 std::string str(u_array, u_array + sizeof(u_array));

Done.

查看更多
登录 后发表回答