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

Ian Burris picture Ian Burris · Jan 22, 2011 · Viewed 88.8k times · Source

What is the best way to convert a C-style string to a C++ std::string? In the past I've done it using stringstreams. Is there a better way?

Answer

templatetypedef picture templatetypedef · Jan 22, 2011

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. :-)