Casting char to string is not working
Jul 3, 2014 at 7:31pm Jul 3, 2014 at 7:31pm UTC
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);
}
Jul 3, 2014 at 7:47pm Jul 3, 2014 at 7:47pm UTC
in the code above, try str = std::string(1,ch);
Jul 3, 2014 at 7:49pm Jul 3, 2014 at 7:49pm UTC
Why isn't it working? But why are you trying to use the cast? Why not just use the operator+ or operator+=?
str += ch;
Jul 3, 2014 at 8:03pm Jul 3, 2014 at 8:03pm UTC
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.