Summary: In this programming tutorial, we will learn different ways to convert a string into a char array in C++.

Method 1: Using ‘for loop’

In this approach, we are iterating through each character of the string value and assigning it to the corresponding index of the char array.

It is important to append ‘\0’ to the end of the char array after the copy operation otherwise, an error will occur.

Method 2: Using strcpy()

In this approach, we are first converting the C++ type string into a C string using the c_str() method. Then we copy the characters of the converted c-type string into the char array using the strcpy() method.

Method 3: Using copy()

In this approach, we are using std::copy() method to copy all characters of the string into the char array.

Method 4: Using string::copy()

In this last approach, we are using inbuilt string library string::copy() method to copy string charaters to char array.

The string::copy() works similar as std::copy().

These are some of the ways we can easily convert any string into four arrays in C++.

Leave a Reply

12 − 7 =