Summary: In this programming tutorial, we will learn to convert a char array into a string in C++.
Example:
char array[] = { 'p', 'e', 'n', 'c', 'i', 'l', ' ', 'p', 'r', 'o', 'g', 'r', 'a', 'm', 'm', 'e', 'r', '\0'}; string = "pencil programmer";
There are different methods to convert an array of characters into a single string value in C++. Let’s look at some methods with examples:
Method 1: Using ‘=’ Operator
Each character in a string
or char
array has an index value. We can easily assign every character to their respective index position in string by using the assignment (=) in C++.
#include <iostream>
using namespace std;
int main()
{
char arry[30];
cout << "Enter into char array: \n";
cin.getline(arry, 30, '\n');
string str = arry;
cout << "String: " << str << endl;
return 0;
}
Note: Use the cin.getline() method for taking input into char array or else the elements after space will be eliminated.
Method 2: Using String Constructor
The string
constructor accepts a char array as a parameter, which is then converted to a string value.
#include <iostream>
using namespace std;
int main()
{
char arry[30];
cout << "Enter into char array \n";
cin.getline(arry, 30, '\n');
string str(arry);
cout << "String: " << str << endl;
return 0;
}
Output of both programs will be the same:

These are the two ways using which we can convert an array of characters into a string value in the C++ programming language.