从1个字符转换成字符串?

我只需要投1个 charstring。相反的方式是相当简单的像 str[0]

下面这些对我来说不起作用:

char c = 34;
string(1,c);
//this doesn't work, the string is always empty.


string s(c);
//also doesn't work.


boost::lexical_cast<string>((int)c);
//also doesn't work.
372424 次浏览

我真的以为选角的方法会很好。既然不行,你可以试试弦流。下面是一个例子:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;

所有的

std::string s(1, c); std::cout << s << std::endl;

还有

std::cout << std::string(1, c) << std::endl;

还有

std::string s; s.push_back(c); std::cout << s << std::endl;

对我有用。

无论你有多少 char变量,这个解决方案都是有效的:

char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};

可以将字符串设置为等于 char。

#include <iostream>
#include <string>


using namespace std;


int main()
{
string s;
char one = '1';
char two = '2';
s = one;
s += two;
cout << s << endl;
}

。/测试
12