我只需要将 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.
所有的
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;
为我工作。
老实说,我认为铸造方法会很好。既然没有,你可以试试 stringstream。下面是一个例子:
#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
无论您拥有多少char
变量,此解决方案都将起作用:
char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};