Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::array<char, N> to std::string

Tags:

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++?

like image 224
Jonathan Evans Avatar asked Jun 05 '12 15:06

Jonathan Evans


People also ask

Should I use std::string or * char?

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.

What does std::string () do?

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.

Is std::string an array?

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.


1 Answers

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)); 
like image 65
Robᵩ Avatar answered Oct 18 '22 03:10

Robᵩ