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; } |
chevron_right
filter_none
Output:
a
Recommended Posts:
- Convert character array to string in C++
- Find the character in first string that is present at minimum index in second string
- Character replacement after removing duplicates from a string
- Program to count occurrence of a given character in a string
- Convert string to char array in C++
- Convert a floating point number to string in C
- How to convert C style strings to std::string and vice versa?
- Check input character is alphabet, digit or special character
- Implementing Iterator pattern of a single Linked List
- How to execute zombie and orphan process in a single program?
- OpenCV C++ Program to create a single colored blank image
- Character arithmetic in C and C++
- Character Classification in C++ : cctype
- Change/add only one character and print '*' exactly 20 times
- Type difference of character literals in C and C++
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 Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



