Search code examples
c++stringtype-conversionchar

How can I create a string from a single character?


I have a single char value, and I need to cast/convert it to a std::string. How can I do this?

I know how to go the opposite way, to retrieve a char from a std::string object: you just need to index the string at the appropriate location. For example: str[0] will retrieve the first character in the string.

But how do I go the other way? I want something like:

char c = 34;
std::string s(c);

…but this doesn't work (the string is always empty).


Solution

  • You can use any/all of the following to create a std::string from a single character:

    • std::string s(1, c);
      
      std::cout << s << std::endl;
      
    • std::string s{c};
      
      std::cout << s << std::endl;
      
    • std::string s;
      s.push_back(c);
      
      std::cout << s << std::endl;