0
Any ideas how to convert a char to string and vice-versa?
Thanks for your time.
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.
+ 7
char to string : char a='1'; string str(1,a);
string to char: impossible unless it's one character long.
+ 6
The name of the string you want to convert into.
+ 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;
}
}
+ 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 :)
0
What is str?
0
No, I didn't mean that. I mean to convert a char value into string
0
Helioform Thanks
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.
- 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' "