Hi there,
I was wondering how you would be able to convert a user-inputted peice of data of type string to a character array. Any ideas?
Printable View
Hi there,
I was wondering how you would be able to convert a user-inputted peice of data of type string to a character array. Any ideas?
You can get a "const char*" by calling "c_str()" on a string object.
gg
I didn't know that, ha, I would have made a loop to do it -- :)
Better yet, if you don't want a const char* use the copy() function:
copy takes two or three parameters:Code:#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
char* buf;
s = "THIS IS A STRING";
buf = new char[s.size()+1];
s.copy(buf,s.size());
cout<<buf;
}
copy(char* buf, int len);
copy(char* buf, int len,int startpos);
It copies at most len characters into the buffer, and with the second function starts copying with a certain character in the std::string...It doesn't null terminate the char* so take that into account
Note: You could also simply use data() which works like c_str() (returns an array of chars) but doesnt append a Null character