Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
641 views
in Technique[技术] by (71.8m points)

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

If the array was null-terminated this would be pretty straight forward:

unsigned char u_array[4] = { 'a', 's', 'd', '' };
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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...