In this C++ tutorial, you will learn how to convert string to char array using Assignment operator, loop statements, or functions like strcpy() and c_str(), with example programs.

C++ String to Char Array

To convert a string to character array in C++, you can directly assign the string to character array, or iterate over the characters of string and assign the characters to the char array, or use strcpy() and c_str() functions. We shall go through each of these approaches with examples.

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

</>
Copy
#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

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

</>
Copy
#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

</>
Copy
#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

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

</>
Copy
#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.