What is the best way to convert from a std::array<char, N>
to a std::string
?
I have tried producing a template method but have had no luck. I think my C++ skills just aren't up to scratch. Is there an idiomatic way of doing this in C++?
Use std::string when you need to store a value. Use const char * when you want maximum flexibility, as almost everything can be easily converted to or from one.
std::string class in C++ C++ has in its definition a way to represent a sequence of characters as an object of the class. This class is called std:: string. String class stores the characters as a sequence of bytes with the functionality of allowing access to the single-byte character.
Now, you know that std::string is the basic_string for char -typed characters. Referring to Does std::string need to store its character in a contiguous piece of memory?, if you are mentioning std::string then for C++ 11 and later versions, it is essentially AN array (not TWO or MORE arrays) of char -typed characters.
I won't say it is the "best way", but a way is to use std::string
's iterator constructor:
std::array<char, 10> arr; ... // fill in arr std::string str(std::begin(arr), std::end(arr));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With