c++stringcstring

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


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?


Solution

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