What is the best way to convert a C-style string to a C++ std::string
? In the past I've done it using stringstream
s. Is there a better way?
The std::string class manages the underlying storage for you, storing your strings in a contiguous manner. You can get access to this underlying buffer using the c_str() member function, which will return a pointer to null-terminated char array. This allows std::string to interoperate with C-string APIs.
std::string is compatible with STL algorithms and other containers. C strings are not char * or const char * ; they are just null-terminated character arrays. Even string literals are just character arrays.
There is no functionality difference between string and std::string because they're the same type.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With