C++ Char Array to String
In this tutorial, we shall write C++ Programs that convert char array to string. 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 a char array to string, you can directly assign the char array with list of characters, to the string variable.
C++ Program
#include <iostream> using namespace std; int main() { string str = {'t','u','t','o','r','i','a','l','k','a','r','t'}; cout << str; }
Output
tutorialkart
Method 2: Use string.append() function
To convert a char array to string, create an empty string and append char array to this empty string. Now, the string contains characters from the char array.
C++ Program
#include <iostream> using namespace std; int main() { string str; char charArr[] = {'t','u','t','o','r','i','a','l','k','a','r','t','\0'}; str.append(charArr); cout << str; }
Please note that the last character in our character array is a null character.
Output
tutorialkart
Method 3: Append each Element of Char Array to String
You can use a looping statement to assign each char in string to char array.
In the following example, we use C++ Foreach statement, to append each char of char array to string.
C++ Program
#include <iostream> using namespace std; int main() { string str = ""; char charArr[] = {'t','u','t','o','r','i','a','l','k','a','r','t'}; for(char ch: charArr) str += ch; cout << str; }
Output
tutorialkart
You may also use for loop with the same logic.
Method 4: Use string constructor
You can also use string constructor to convert a char array to string. Pass the char array as argument to string constructor. This string will be initialized with the characters from char array.
C++ Program
#include <iostream> using namespace std; int main() { char charArr[] = {'t','u','t','o','r','i','a','l','k','a','r','t'}; string str(charArr); cout << str; }
Output
tutorialkart
Conclusion
In this C++ Tutorial, we learned how to convert a char array to string, with the help of example C++ programs.