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

前端 未结 12 2238
别跟我提以往
别跟我提以往 2020-12-02 20:25

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

unsigned char u_array[4] = { \'a\', \'s\', \'d\', \'\\0\' };
std::string str         


        
12条回答
  •  孤街浪徒
    2020-12-02 20:29

    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 
    #include 
    #include 
    
    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.

提交回复
热议问题