3

Is there a simple way of creating a std::string out of an const char[] ?

I mean something simpler then:

std::stringstream stream;
stream << const_char;

std::string string = stream.str();

5 Answers 5

17

std::string has multiple constructors, one of which is string( const char* str );.

You can use it like this:

std::string myString(const_char);

You could also use assignment, if you need to set the value at some time later than when the variable is declared:

myString = const_char;
11

std::string has a constructor that takes a const char*, so you can just do:

const char* charArray;
std::string str(charArray);
2
std::string str = const_char;
1

Just use the std::string constructor. You can pass it a char*:

char* charArray = "My String";
std::string stdstr( charArray );
0

If you want to convert it without creating an additional variable, such as passing an argument to a function in just one line, try this:

std::string() + const_char

This creates an empty string using std::string's default constructor and concatenates your const char[] or const char* to it to result in type std::string.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.