This post will discuss how to convert a string to a char array in C++.

1. Using strcpy function

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

Download  Run Code

Output:

Hello World!

2. Using std::string::copy function

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. Using std::copy function

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

Download  Run Code

Output:

Hello World!

That’s all about converting a string to a char array in C++.