如何在C ++ STL中将字符转换为字符串?
将字符转换为字符串
有时,可能需要将字符变量转换为字符串变量。在C++中,我们可以通过调用字符串类的构造函数来实现。例如,'a'将被转换为“a”。
'a'是一个字符,而“a”是一个字符串值,
charc='a';
字符串s(1,c);//s=“c”
C++字符串构造器详细信息
原型:
string(int, char);
参数:
int n;//n=1
char c;返回类型:从概念上讲,它正在返回(实际上是在构造)字符串。但是实际上,由于它是构造函数,因此没有返回类型。
示例
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.";请记住,需要在“”下定义一个字符串变量(文字)。“a”是字符,而“a”是字符串。
需要的头文件:
#include <string>
Or
#include <bits/stdc++.h>C++程序将字符转换为字符串
#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;
}输出结果
Input character to convert I Converted to string: I