Convert string to char array in C++

3.1

Many of us have encountered error ‘cannot covert std::string to char[] or char* data type’.

Examples:

Input : string s = "geeksforgeeks" ;
Output : char s[] = { 'g', 'e', 'e', 'k', 's', 'f', 'o',
                     'r', 'g', 'e', 'e', 'k', 's' } ;

Input : string s = "coding" ;
Output : char s[] = { 'c', 'o', 'd', 'i', 'n', 'g' } ;

A way to do this is to copy the contents of the string to char array. This can be done with the help of c_str() and strcpy() function.
The c_str() function is used to return a pointer to an array that contains a null terminated sequence of character representing the current value of the string.

Syntax:

const char* c_str() const ;

If there is an exception thrown then there are no changes in the string. But when we need to find or access the individual elements then we copy it to a char array using strcpy() function. After copying it, we can use it just like a simple array.
The length of the char array taken should not be less than the length of input string.

// CPP program to convert string 
// to char array
#include <bits/stdc++.h>
using namespace std;

// driver code
int main()
{
    // assigning value to string s
    string s = "geeksforgeeks";

    int n = s.length(); 
    
    // declaring character array
    char char_array[n+1]; 
    
    // copying the contents of the 
    // string to char array
    strcpy(char_array, s.c_str()); 
    
    for (int i=0; i<n; i++)
      cout << char_array[i];    

    return 0;
} 

Output:

geeksforgeeks

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



3.1 Average Difficulty : 3.1/5.0
Based on 6 vote(s)