I have seen many similar questions but none that seem to be working for my code, I think I am overlooking something basic, maybe you can help.
Right now I'm constructing a string to be sent as a request to the winsock send function, which requires a char [] to be sent. I need to convert my std::string into a char array (char []).
Currently this is the request that works:
char request [] = "GET /gwc/cgi-bin/fc?client=udayton0.1&hostfile=1HTTP/1.0\nHost:www.gofoxy.net\n\n";
But I need to change a string of a request to the same data structure.
I appreciate any help!
edit:
I can convert a string to a char *, but how can I use that to get a character array? I hope I'm not making it more confusing. Here are two attempts that produce char star's that aren't compatible with the send request when I run:
//convert request into a char[]
//char *req_ch = new char[req_str.size()+1];
//hostCh[req_str.size()] = 0;
//memcpy(req_ch, req_str.c_str(), req_str.size());
//char * req = new char[req_str.size() +1];
//std::copy(req_str.begin(), req_str.end(), req);
//req[req_str.size()] = '\0';
If you have some legacy C-style API with a signature like this, where it is expecting a null terminated C-style string:
void foo(const char* data);
then you can typically do something like:
std::string s("my string data");
foo(s.c_str());
If you really need an array, or a non-const version of the data, so that the API is this:
void foo(char* data, std::size_t len); // or foo(char[] data, std::size_t len);
Then you could do something like this:
std::string s("my string data");
std::vector<char> v(s.begin(), s.end());
foo(&v[0], v.size()); // or foo(v.data(), v.size()); in C++11
Do you really need char[] or will char const* do?
If the latter, c_str() will do what you want.
If the former then you'll need to copy the string into something that does what you want:
std::vector<char> buff(str.size() + 1); // initializes to all 0's.
std::copy(str.begin(), str.end(), buff.begin());
fun_call(&buff[0]);
Chances are that you only need the c_str version. If you're needing this second version then you're reading and probably, hopefully, providing a buff max size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With