155

我只需要将 1char转换为string. 相反的方式很简单,比如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.
4

3 回答 3

219

所有的

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;

为我工作。

于 2013-06-19T21:32:26.620 回答
11

老实说,我认为铸造方法会很好。既然没有,你可以试试 stringstream。下面是一个例子:

#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
于 2013-06-19T21:28:58.410 回答
7

无论您拥有多少char变量,此解决方案都将起作用:

char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};
于 2020-10-17T21:33:53.227 回答