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’

#include <iostream>
using namespace std;
 
int main()
{
    string str;
    cout << "Enter a string \n";
    getline(cin,str);  
 
    //Create an empty char array of the same size
    char arry[str.size()];
 
    //Loop through the string and assign each character to the array
    for(int i=0; i<str.size(); i++){
        arry[i] = str[i];
    }
 
    cout << "String: "<< str << endl;
    cout << "char Array: " << arry << endl;
    return 0;
}

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()

#include <iostream>
#include <cstring>  //For strcpy()
using namespace std;
 
int main()
{
    string str;
    cout << "Enter a string \n";
    getline(cin,str); 
 
    //create an empty char array
    char arry[str.size()+1];
 
    //convert C++_string to c_string and copy it to char array using strcpy()
    strcpy(arry,str.c_str());
 
    cout << "String: "<< str << endl;
    cout << "char Array: " << arry << endl;
    return 0;
}

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()

#include <iostream>
using namespace std;
 
int main()
{
    string str;
    cout << "Enter a string \n";
    getline(cin,str);     
    
    //create an char array of the same size 
    char arry[str.size()];
 
    //convert using copy() method
    copy(str.begin(), str.end(), arry);
 
    cout << "String: "<< str << endl;
    cout << "char Array: " << arry << endl;
    return 0;
}

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()

#include <iostream>
using namespace std;
 
int main()
{
    string str;
    cout << "Enter a string \n";
    getline(cin,str);      
    
    //create an char array of the same size
    char arry[str.size()];
 
    //converting c++_string to c_string and copying it to char array
    str.copy(arry, str.size());
 
    cout << "String: "<< str << endl;
    cout << "char Array: " << arry << endl;
    return 0;
}

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

seventeen − 4 =