Casting char to string is not working

I am trying to take a character from a string and store it in a string vector, and I know I need to cast the character to a string first, but it's not working. I can't even get the simple code below to compile, any suggestions?

I get invalid conversion from char to const char*.

1
2
3
4
5
6
7
8
 #include <iostream>
#include <string>

int main() {
char ch = 'k';
std::string str;
str = std::string(ch);
}
in the code above, try str = std::string(1,ch);
Why isn't it working? But why are you trying to use the cast? Why not just use the operator+ or operator+=?

str += ch;

You already have two good answers - either choose an appropriate constructor for std::string, or construct an empty string and concatenate the char.

But if you did need to convert a char into a char *, you could do this;
1
2
3
4
5
6
7
    char ch = 'k';
        
    char buf[2];
    buf[0] = ch;
    buf[1] = 0;  // null terminator
    
    std::string str(buf);
Topic archived. No new replies allowed.