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

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

    You can use this std::string constructor:

    string ( const char * s, size_t n );
    

    so in your example:

    std::string str(u_array, 4);
    
    0 讨论(0)
  • 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 <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.

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

    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;
    }
    
    0 讨论(0)
  • 2020-12-02 20:30

    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.

    0 讨论(0)
  • Try:

    std::string str;
    str.resize(4);
    std::copy(u_array, u_array+4, str.begin());
    
    0 讨论(0)
  • 2020-12-02 20:32

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

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

    0 讨论(0)
提交回复
热议问题