How to convert a single character to string in C++?

How to convert a single character to a string object.

Examples:

Input :  x = 'a'
Output : string s = "a"

Input :  x = 'b'
Output : string s = "b"



The idea is to use string class which 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.

// Create a string of size n and fill
// the string with character x.
string s(int n, char x);
// 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;
}
Output:

a



If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1 Average Difficulty : 1/5.0
Based on 2 vote(s)