C++ String to Char Array

In this tutorial, we shall write C++ Programs that convert string to char array. There are many ways to convert a string to an array of characters. We shall go through some of them.

Method 1: Assign String Literal to the Char Array

To convert string to char array, you can directly assign the char array variable with a string constant.

C++ Program

#include <iostream>
using namespace std;

int main() {
   char charArr[] = "tutorialkart";

   for(char ch: charArr)
      cout << ch << "  ";
}

Output

t  u  t  o  r  i  a  l  k  a  r  t

Method 2: Assign Each Character of String to Char Array

You can use a looping statement to assign each char in string to char array.

In the following example, we use while loop, to convert a string to char array.

C++ Program

#include <iostream>
using namespace std;

int main() {
   string str = "tutorialkart";
   char charArr[str.length()];

   int i=0;
   while (i < str.length()) {
      charArr[i] = str[i];
      i++;
   }

   for(char ch: charArr)
      cout << ch << "  ";
}

Output

t  u  t  o  r  i  a  l  k  a  r  t

You may also use for loop with the same logic.

C++ Program

#include <iostream>
using namespace std;

int main() {
   string str = "tutorialkart";
   char charArr[str.length()];

   for (int i=0; i < str.length(); i++) {
      charArr[i] = str[i];
   }

   for(char ch: charArr)
      cout << ch << "  ";
}

Output

t  u  t  o  r  i  a  l  k  a  r  t

Method 3: Use strcpy() and c_str()

c_str() returns a const pointer to null terminated contents. Of course in this case, the contents are characters in the string.

strcpy() copies const char pointer to char pointer. To use strcpy(), you must include bits/stdc++.h at the start of your program.

C++ Program

#include <iostream>
#include <bits/stdc++.h> 
using namespace std;

int main() {
   string str = "tutorialkart";
   char charArr[str.length()];
   strcpy(charArr, str.c_str());

   for(char ch: charArr)
      cout << ch << "  ";
}

Output

t  u  t  o  r  i  a  l  k  a  r  t

Conclusion

In this C++ Tutorial, we learned how to convert a string to char array, with the help of example C++ programs.