Convert char array to a string in C++

In this post, we will discuss how to convert a char array to a C++ string.


1. String constructor

The string class provides a constructor which can accept a c-string (a null-terminated character sequence). It has following prototype:

string (const char* s);

where s is a pointer to an array of characters (such as a c-string).


Download   Run Code


Techie Delight


2. operator=

Another alternative is to directly assign a char[] to a std::string as shown below. This works as operator= is overloaded for std::string and a c-string would be copied to the string.

string& operator= (const char* s);


Download   Run Code


Techie Delight

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂

Get great deals at Amazon


Leave a Reply

Notify of