How to convert a single character to string in C++?


There are several methods to convert a single character to a string. In the following example, some of them are used to convert a character to a string.

Here is an example of converting a single character to string in C++ language,

Example

 Live Demo

#include <iostream>
#include<string>
#include<sstream>

int main() {
   char c = 'm';

   std::string s(1, c);
   std::cout << "Using string constructor : " << s << '\n';

   std::string s2;
   std::stringstream s1;
   s1 << c;
   s1 >> s;
   std::cout << "Using string stream : " << s << '\n';

   s2.push_back(c);
   std::cout << "Using string push_back : " << s2 << std::endl;

   return 0;
}

Output

Here is the output

Using string constructor : m
Using string stream : m
Using string push_back : m

In the above program, three methods are used to convert a character to a string. First, using string constructor

std::string s(1, c);

Second, using string stream

std::string s2;
std::stringstream s1;
s1 << c;
s1 >> s;

Third, using string push_back

s2.push_back(c);

Updated on: 25-Jun-2020

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements