Converting a C-style string to a C++ std::string

C++ strings have a constructor that lets you construct a std::string directly from a C-style string:

const char* myStr = "This is a C string!";
std::string myCppString = myStr;

Or, alternatively:

std::string myCppString = "This is a C string!";

As @TrevorHickey notes in the comments, be careful to make sure that the pointer you're initializing the std::string with isn't a null pointer. If it is, the above code leads to undefined behavior. Then again, if you have a null pointer, one could argue that you don't even have a string at all. :-)


Check the different constructors of the string class: documentation You maybe interested in:

//string(char* s)
std::string str(cstring);

And:

//string(char* s, size_t n)
std::string str(cstring, len_str);

C++11: Overload a string literal operator

std::string operator ""_s(const char * str, std::size_t len) {
    return std::string(str, len);
}

auto s1 = "abc\0\0def";     // C style string
auto s2 = "abc\0\0def"_s;   // C++ style std::string

C++14: Use the operator from std::string_literals namespace

using namespace std::string_literals;

auto s3 = "abc\0\0def"s;    // is a std::string

If you mean char* to std::string, you can use the constructor.

char* a;
std::string s(a);

Or if the string s already exist, simply write this:

s=std::string(a);

You can initialise a std::string directly from a c-string:

std::string s = "i am a c string";
std::string t = std::string("i am one too");