C++ convert from 1 char to string?

weeo picture weeo · Jun 19, 2013 · Viewed 267.3k times · Source

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.

Answer

Massa picture Massa · Jun 19, 2013

All of

std::string s(1, c); std::cout << s << std::endl;

and

std::cout << std::string(1, c) << std::endl;

and

std::string s; s.push_back(c); std::cout << s << std::endl;

worked for me.