We are given a char array and is asked to convert it into string data type in C++.

Example:

For this we take input into char array then we convert it into a string using two different approaches:

Char Array to String in C++ using ‘=’ Operator

Each character in string and char array has index value. So, by using ‘=’ operator we can directly assign each character to their respective index position in string.

Note: use gets() method in stdio.h library for taking input into char array or else the elements after space will be eliminated.

Char Array to String in C++ using String Constructor

Inbuilt string constructor accepts char array as a parameter which it then uses it as a string.

Output of both programs will be the same.

char array to string in C++ output

Any doubt comment below.

Leave a Reply

Close Menu