Home » C++ » C++ convert from 1 char to string? [closed]

C++ convert from 1 char to string? [closed]

Posted by: admin November 29, 2017 Leave a comment

Questions:

I really didn’t find any answer that close…

the opposite way is pretty simple like str[0]

But I need to cast only 1 char to string…

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
Answers:

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.

Questions:
Answers:

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>
stringstream ss;
string target;
char mychar='a';
ss << mychar;
ss >> target;