简体   繁体   English

将std :: string转换为char数组

[英]Converting an std::string into a char array

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. 现在,我正在构造一个字符串,该字符串将作为请求发送给winsock send函数,该函数需要发送char []。 I need to convert my std::string into a char array (char []). 我需要将std :: string转换为char数组(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? 我可以将字符串转换为char *,但是如何使用它来获取字符数组? 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: 这是我运行时产生与发送请求不兼容的char star的两次尝试:

//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: 如果您有一些带有此类签名的旧式C风格API,则期望以null结尾的C风格字符串:

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: 如果您确实需要数据的数组或非const版本,那么API就是这样的:

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? 您是否真的需要char[]char const*需要?

If the latter, c_str() will do what you want. 如果是后者,c_str()会做您想要的。

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. 您可能只需要c_str版本。 If you're needing this second version then you're reading and probably, hopefully, providing a buff max size. 如果您需要第二个版本,那么您正在阅读,并可能希望提供buff最大大小。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM