1

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.

1

2 Answers 2

2

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 );
Sign up to request clarification or add additional context in comments.

5 Comments

Sounds like a bad idea without an explicit null terminator in the array.
@dave And why do you have decided that there is no null terminating character?
There should be 252 null terminators in that array. :-)
@dave I though the same thing and then remembered that all missing initializers are set to 0, so it has 252 null terminators in it.
Ah right, didn't see the 256 size. That's ok then in this case
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.