Home > Software engineering >  Create std::string from int8_t array
Create std::string from int8_t array

Time:11-24

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.

CodePudding user response:

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 );

CodePudding user response:

std::string like other containers can be constructed using a pair of iterators. This constructor will use implicit conversions if available, such as converting int8_t to char.

int8_t title[256] = {'a', 'e', 'w', 's'};
std::string s(std::begin(title), std::end(title));

Note that this solution will copy the whole array, including the unused bytes. If the array is often much larger than it needs to be, you can look for the null terminator instead

int8_t title[256] = {'a', 'e', 'w', 's'};
auto end = std::find(std::begin(title), std::end(title), '\0');
std::string s(std::begin(title), end);
  • Related