Preferred conversion from char (not char*) to std::string

pythonic metaphor picture pythonic metaphor · Jan 18, 2011 · Viewed 28.1k times · Source

I have a char, a plain old character, that I would like to turn into an std::string. std::string(char) doesn't exist of course. I could create an char array and copy it in, I could go through string streams, or many other little roundabout routes. Currently, I prefer boost::lexical_cast, but even that seems too verbose for this simple task. So what's the preferred way?

Answer

Daniel Gallagher picture Daniel Gallagher · Jan 18, 2011

std::string has a constructor that takes a number and a character. The character will repeat for the given number of times. Thus, you should use:

std::string str(1, ch);