In this C++ tutorial, you will learn how to convert a character array to a string using assignment operator, std::string::append() function, or a For loop statement, with examples.
Convert Char Array to String in C++
To convert a char array to a string in C++, you can directly assign the char array to the string variable, pass the char array as argument to the string::append() function, use string constructor, or use a loop statement like For loop to create the string from characters in the array.
We shall go through these two ways of converting a given char array to a string.
Method 1: Assign String Literal with 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.