Home >Backend Development >C++ >How to Convert a Single Character to a std::string in C ?
Creating a String from a Single Character
One may encounter the need to convert a single character, represented as a char data type, into a std::string. Acquiring a character from a string is straightforward, simply index the string at the desired location. However, the converse process requires a different approach.
To create a std::string from a single character, several methods are available:
<code class="cpp">char c = 34; std::string s(1, c); std::cout << s << std::endl;</code>
This method initializes the string with a single character, effectively converting it to a string.
<code class="cpp">char c = 34; std::string s{c}; std::cout << s << std::endl;</code>
Similar to the previous method, the braced initializer syntax automatically constructs a string from the provided character.
<code class="cpp">char c = 34; std::string s; s.push_back(c); std::cout << s << std::endl;</code>
This method creates an empty string and appends the character to it, resulting in a string containing the desired character.
The above is the detailed content of How to Convert a Single Character to a std::string in C ?. For more information, please follow other related articles on the PHP Chinese website!