Search code examples
c++castingcharintegerstdstring

Create std::string from int8_t array


In some code int8_t[] type is used instead of char[].

int8_t title[256] = {'a', 'e', 'w', 's'};
std::string s(title); // compile error: no corresponding constructor

How to properly and safely create a std::string from it?

When I will do cout << s; I want that it print aews, as if char[] type was passed to the constructor.


Solution

  • Here you are

    int8_t title[256] = { 'a', 'e', 'w', 's' };
    std::string s( reinterpret_cast<char *>( title ) );
    std::cout << s << '\n';
    

    Or you may use also

    std::string s( reinterpret_cast<char *>( title ), 4 );