Home »
C++ STL
How to convert a character to string in C++ STL?
C++ STL | converting a character to string: In this article we are going to see how we can convert a character to string in C++?
Submitted by Radib Kar, on February 27, 2019
Converting character to string
Sometimes, It may be needed to convert a character variable to a string variable. In C++, we can do this by calling the constructor of the string class. For example, 'a' will be converted to "a".
'a' is a character, whereas "a" is a string value,
char c = 'a';
string s(1,c); //s = "c"
C++ String Constructor details
Prototype:
string(int, char);
Parameter:
int n;//n=1
char c;
Return type: Conceptually it's returning (constructing actually) the string. But actually since it's constructor it has no return type.
Example:
Like we define and declare,
char c='I';
string s(1,c); //s="I"
if(s=="I")
cout<<"converted to string";
else
cout<<"Failed to convert.";
Remember, a string variable (literal) need to be defined under "". 'a' is a character whereas "a" is a string.
Header file needed:
#include <string>
Or
#include <bits/stdc++.h>
C++ program to convert a character to the string
#include <bits/stdc++.h>
using namespace std;
int main(){
char c;
cout<<"Input character to convert\n";
cin>>c;
string s(1,c);
cout<<"Converted to string: "<<s<<endl;
return 0;
}
Output
Input character to convert
I
Converted to string: I