Shinigamisan
0
Q:

convert char to string - c++

// CPP program to get a string from single 
// character. 
#include<bits/stdc++.h> 
using namespace std; 
  
string getString(char x) 
{ 
    // string class has a constructor 
    // that allows us to specify size of 
    // string as first parameter and character 
    // to be filled in given size as second 
    // parameter. 
    string s(1, x); 
  
    return s;    
} 
  
int main() { 
  cout << getString('a'); 
  return 0; 
} 
1
// 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; 
} 
0
// example
char sczName[] = {"Jakes"};
std::string strName = std::string(sczName);

/* SYNTAX
#include <string>
std::string(<char-to-convert>)
*/
1
#include <iostream>
using namespace std;

int main()
{
  char c = 'l';
  string str;
  str.push_back(c);
}
1
std::cout << std::string(1, c) << std::endl;
1

New to Communities?

Join the community