I have a single char value and want to create a std::string from it. I know how to get a char from a string using indexing (e.g., str[0]), but I’m unsure how to do the opposite. For example, this doesn’t work:
char c = 34;
std::string s(c); // string ends up empty
What is the correct way to convert a char to string C++?
Hey! I’ve done this exact thing many times
. The issue with std::string s(c); is that it expects a C-string pointer, not a single character. The easiest fix is:
char c = 'A';
std::string s(1, c); // 1 is the count
std::cout << s << std::endl; // Output: A
The constructor std::string(size_t n, char c) creates a string with n copies of the character.
Works perfectly when you just want a single-character string.
Another simple method I often use:
char c = 'B';
std::string s = "" + std::string(1, c); // or ""s + c with C++14 literals
std::cout << s << std::endl; // Output: B
You can also use C++14 string literals for cleaner code:
using namespace std::string_literals;
std::string s = c + ""s;
This is handy when concatenating multiple chars or combining with other strings.
If you already have an empty string, you can append a character:
char c = 'C';
std::string s;
s.push_back(c);
std::cout << s << std::endl; // Output: C
I use this when building strings dynamically character by character.
Very readable and safe, no weird constructor issues.