Convert a string to char array in C++

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

 

1. strcpy function

The idea is to use c_str() function to convert the std::string to a c-string. Then we can simply call strcpy() function to copy the c-string into a char array.

 

Download   Run Code

Output:

Hello World!

 

2. std::string::copy

We know that the strcpy() is a C function. We can avoid using that in C++ by using std::string::copy instead.

 

Download   Run Code

Output:

Hello World!

 

3.std::copy

Finally, the <algorithm> header also provides the standard copy algorithm std::copy which can be used in below manner:

 

Download   Run Code

Output:

Hello World!

 
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




Categories

Leave a Reply

Notify of
avatar
wpDiscuz