Convert Array to String
Convert Array to String in C++ (5 Programs)
BeginnerTopic: String Conversion Programs
C++ Convert Array to String Program
This program helps you to learn the fundamental structure and syntax of C++ programming.
#include <iostream>
#include <string>
using namespace std;
int main() {
char arr[] = {'H', 'e', 'l', 'l', 'o', '\0'};
// Method 1: Direct assignment
string str1 = arr;
// Method 2: Using string constructor
string str2(arr);
// Method 3: Using assign()
string str3;
str3.assign(arr);
cout << "Array: " << arr << endl;
cout << "String (method 1): " << str1 << endl;
cout << "String (method 2): " << str2 << endl;
cout << "String (method 3): " << str3 << endl;
return 0;
}Output
Array: Hello String (method 1): Hello String (method 2): Hello String (method 3): Hello
Understanding Convert Array to String
This program demonstrates 5 different methods to convert a character array to a string: direct assignment, using string constructor, using assign(), using append(), and using stringstream.
Note: To write and run C++ programs, you need to set up the local environment on your computer. Refer to the complete article Setting up C++ Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your C++ programs.