convert char* to string c++ code example

Example 1: convert string to char c++

// "std::string" has a method called "c_str()" that returns a "const char*"
// pointer to its inner memory. You can copy that "const char*" to a variable
// using "strcpy()".

std::string str = "Hello World";
char buffer[50];

strcpy(buffer, str.c_str());

std::cout << buffer;	//Output: Hello World

//POSTED BY eferion ON STACK OVERFLOW (IN SPANISH).

Example 2: c++ cast char to string

// example
char sczName[] = {"Jakes"};
std::string strName = std::string(sczName);

/* SYNTAX
#include <string>
std::string(<char-to-convert>)
*/

Example 3: COnvert string to char * C++

// CPP program to convert string 
// to char array 
#include <bits/stdc++.h> 
  
using namespace std; 
  
// driver code 
int main() 
{ 
    // assigning value to string s 
    string s = "geeksforgeeks"; 
  
    int n = s.length(); 
  
    // declaring character array 
    char char_array[n + 1]; 
  
    // copying the contents of the 
    // string to char array 
    strcpy(char_array, s.c_str()); 
  
    for (int i = 0; i < n; i++) 
        cout << char_array[i]; 
  
    return 0; 
}

Example 4: C++ int to char*

std::string s = std::to_string(number);
char const *pchar = s.c_str();  //use char const* as target type

Example 5: char to string c++

std::cout << std::string(1, c) << std::endl;

Example 6: c++ char to string

#include <iostream>
using namespace std;

int main()
{
  char c = 'l';
  string str;
  str.push_back(c);
}

Tags: