I need to cast only 1 char
to string
. The opposite way is pretty simple like str[0]
.
The following did not work for me:
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.
I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
This solution will work regardless of the number of char
variables you have:
char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};
Source: Stackoverflow.com