Summary: In this programming example, we will learn different ways to convert char* to string in C++.

In C++, char* and char array are almost identical (they both store reference), therefore we can easily convert a pointer into a string variable like we converted char array to a string.

Here are some of the methods using which we can convert a char* to string in C++:

Method 1: Using ‘=’ Operator

Since each character in the string has an index value, using the = operator we can assign every character of the char pointer array to their same corresponding index position in the string variable.


#include <iostream>
using namespace std;
 
int main() {
  char *ch = "Pencil Programmer";
 
  string str = ch;

  cout << str;
}

Output:

Pencil Programmer

Method 2: Using String Constructor

The inbuilt string constructor of the String class accepts the char pointer array as an argument that implicitly changes and assigns the argument to a string value.

#include <iostream>
using namespace std;
 
int main() {
  char *ch = "Char Pointer";
 
  //Using string constructor for conversion
  string str(ch);
 
  cout << str;
}

Output:

Char Pointer

These are two simple ways we can use to convert a char pointer array into a string variable in the C++ programming language.

Leave a Reply