I really didn't find any answer that close...
我真的没有找到任何答案。
the opposite way is pretty simple like str[0]
相反的方法很简单,像str[0]
But I need to cast only 1 char to string...
但是我只需要将1个字符转换成字符串……
like this:
是这样的:
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 return null
2 个解决方案
#1
120
All of
所有的
string s(1, c); std::cout << s << std::endl;
and
和
std::cout << string(1, c) << std::endl;
and
和
string s; s.push_back(c); std::cout << s << std::endl;
worked for me.
为我工作。
#2
6
I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
我真诚地认为铸造方法会很有效。既然没有,你可以试试stringstream。下面就是一个例子:
#include <sstream>
#include <string>
stringstream ss;
string target;
char mychar='a';
ss << mychar;
ss >> target;
#1
120
All of
所有的
string s(1, c); std::cout << s << std::endl;
and
和
std::cout << string(1, c) << std::endl;
and
和
string s; s.push_back(c); std::cout << s << std::endl;
worked for me.
为我工作。
#2
6
I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
我真诚地认为铸造方法会很有效。既然没有,你可以试试stringstream。下面就是一个例子:
#include <sstream>
#include <string>
stringstream ss;
string target;
char mychar='a';
ss << mychar;
ss >> target;