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

前端 未结 12 2201
别跟我提以往
别跟我提以往 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:32

    There is a still a problem when the string itself contains a null character and you try to subsequently print the string:

    char c_array[4] = { 'a', 's', 'd', 0 };
    
    std::string toto(array,4);
    cout << toto << endl;  //outputs a 3 chars and a NULL char
    

    However....

    cout << toto.c_str() << endl; //will only print 3 chars.
    

    Its times like these when you just want to ditch cuteness and use bare C.

    0 讨论(0)
  • 2020-12-02 20:37

    This should do it:

    std::string s(u_array, u_array+sizeof(u_array)/sizeof(u_array[0]));
    
    0 讨论(0)
  • 2020-12-02 20:41

    You can create a character pointer pointing to the first character, and another pointing to one-past-the-last, and construct using those two pointers as iterators. Thus:

    std::string str(&u_array[0], &u_array[0] + 4);
    
    0 讨论(0)
  • 2020-12-02 20:41

    std::string has a constructor taking an array of char and a length.

    unsigned char u_array[4] = { 'a', 's', 'd', 'f' };
    std::string str(reinterpret_cast<char*>(u_array), sizeo(u_array));
    
    0 讨论(0)
  • 2020-12-02 20:42

    Ew, why the cast?

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

    Done.

    0 讨论(0)
  • 2020-12-02 20:50

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

    std::string str(reinterpret_cast<char*>(u_array), 4);
    
    0 讨论(0)
提交回复
热议问题