0

Any ideas how to convert a char to string and vice-versa?

Thanks for your time.

9th May 2017, 5:10 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
10 Answers
+ 7
....?? You call the string constructor with the parameters like I've written... string mystring(1, 'x'); for example for char='x'. it will create a string of length 1 with 'x' in it.
9th May 2017, 5:57 PM
Karl T.
Karl T. - avatar
+ 7
char to string : char a='1'; string str(1,a); string to char: impossible unless it's one character long.
9th May 2017, 5:23 PM
Karl T.
Karl T. - avatar
+ 6
The name of the string you want to convert into.
9th May 2017, 5:47 PM
Karl T.
Karl T. - avatar
+ 3
This seem to convert a string in a char array #include<iostream> using namespace std; int main() { string str = "ciao"; char chr[4]; for(int x = 0; x < 4; x++) { chr[x] = str[x]; cout << chr[x] << endl; } }
9th May 2017, 5:47 PM
Emore Anzolin
Emore Anzolin - avatar
+ 3
You can use a function for string-cstring and the constructor for the other way. //#include <string> //#include <cstring> string s = "foobar"; char* ch = new char [s.length () + 1]; strcpy (ch, s.c_str ()); // ch is now a c string. Do stuff with it, then... delete [] ch; The constructor way: char* ch = "convert me"; string str = ch; I hope this helps. happy coding :)
10th May 2017, 8:49 PM
Zeke Williams
Zeke Williams - avatar
0
What is str?
9th May 2017, 5:46 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
0
No, I didn't mean that. I mean to convert a char value into string
9th May 2017, 5:53 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
0
Helioform Thanks
9th May 2017, 8:29 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
0
Hmm I've never thought it like that. You are right alex. SoloLearn should definitely include that in lesson about strings and chars. Fortunately there is community and it's really good.
9th May 2017, 8:33 PM
Γιάννης Δημητριάδης
Γιάννης Δημητριάδης - avatar
- 1
Strings are just an array of chars. You can treat it like an array and use do somethint like "char foo = mystring[2];" And if you want to add onto a string, you simply do "mystring += 'p' "
9th May 2017, 8:30 PM
aklex
aklex - avatar