C++ convert from 1 char to string?

Total
0
Shares

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.

Solution

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.

Source: StackOverflow.com

Leave a Reply

Your email address will not be published. Required fields are marked *