This post will discuss various methods to convert a char to a string in C++.

1. Using std::string constructor

A simple solution is to use the string class fill constructor string (size_t n, char c); which fills the string with n copies of character c.

Download  Run Code

2. Using std::stringstream function

Another good alternative is to use a string stream to convert between strings and other numerical types. The idea is to insert the given character into a stream and then write the contents of its buffer to the std::string.

Download  Run Code

3. Using std::string::push_back function

Another commonly used solution is to use the push_back() function, which is overloaded for chars and appends a character to the string’s end.

Download  Run Code

4. Using std::string::operator+=

string& operator+= (char c);

The string +=operator is overloaded for chars. We can use it to append a character at the end of the string, as shown below:

Download  Run Code

5. Using std::string::operator=

string& operator= (char c);

Similar to the +=operator, the =operator is also overloaded for chars. We can use it to replace the contents of a string with a single char.

Download  Run Code

6. Using std::string::append function

string& append (size_t n, char c);

We can also use the append() function to append n copies of character c, as demonstrated below:

Download  Run Code

7. Using std::string::assign function

string& assign (size_t n, char c);

The assign() function replaces the current value of the string with n copies of character c. We can use it, as shown below:

Download  Run Code

8. Using std::string::insert function

string& insert (size_t pos, size_t n, char c);

We can use insert() that inserts n copies of character c beginning at character pos.

Download  Run Code

9. Using std::string::replace function

string& replace (size_t pos, size_t len, size_t n, char c);

The replace() function replaces the portion of the string (len characters beginning at character pos) by n copies of character c. We can use it, as shown below:

Download  Run Code

10. Converting char to C-string

Finally, we can also convert the char to a C-string and then convert the C-string to a std::string using the fill constructor or std::string::append or std::string::assign.

Download  Run Code

That’s all about converting a char to a string in C++.