Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 239
Ian Burris Avatar asked Jan 21 '11 23:01

Ian Burris


People also ask

Is there std::string in C?

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.

What is a difference between the std::string and C style strings?

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.

Is std::string the same as string?

There is no functionality difference between string and std::string because they're the same type.


2 Answers

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

like image 187
templatetypedef Avatar answered Sep 20 '22 19:09

templatetypedef


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); 
like image 44
Santiago Alessandri Avatar answered Sep 19 '22 19:09

Santiago Alessandri