简体   繁体   English

字符串转换为const char *问题

[英]string conversion to const char * problems

I have this problem that whenever I try to send my post_data1 by libcurls http post it says wrong password, but when I use the fixed expression in post_data2 it logs me in. And when I cout both they are the exact same string.. 我有这个问题,每当我尝试通过libcurls http发送我的post_data1时,都会说出错误的密码,但是当我在post_data2中使用固定表达式时,它将登录我。当我退出时,它们都是完全相同的字符串。

Can anyone tell me why they are not the same when libcurl put them in the header? 谁能告诉我为什么libcurl将它们放在标头中的原因不一样? Or why they differ before I send them if that is the case. 或者,如果是这样的话,为什么在我发送它们之前它们会有所不同。

string username = "mads"; string password = "123"; 
stringstream tmp_s;
tmp_s << "username=" << username << "&password=" << password;
static const char * post_data1 = tmp_s.str().c_str();
static const char * post_data2 = "username=mads&password=123";

std::cout << post_data1 << std::endl;  // gives username=mads&password=123
std::cout << post_data2 << std::endl;  // gives username=mads&password=123

// Fill postfields
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data1);

// Perform the request, res will get the return code
res = curl_easy_perform(curl);

When you use tmp_s.str() you get a temporary string. 当您使用tmp_s.str()会得到一个临时字符串。 You can not save a pointer to it. 您无法保存指向它的指针。 You have to save it to a std::string and use that string in the call: 您必须将其保存到std::string并在调用中使用该字符串:

std::string post_data = tmp_s.str();

// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());

If (and only if) curl_easy_setopt copies the string (and not save just the pointer) you can use tmp_s in the call instead: 如果(且仅当) curl_easy_setopt 复制了字符串(而不仅仅是保存指针),则可以在调用中使用tmp_s

// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, tmp_s.str().c_str());

But I don't know if the function copies the string or just saves the pointer, so the first alternative (to use a std::string ) is probably the safest bet. 但我不知道该函数是复制字符串还是仅保存指针,因此第一种选择(使用std::string )可能是最安全的选择。

static const char * post_data1 = tmp_s.str().c_str();

Is a problem. 是个问题。 It returns a string object and then gets a pointer to the internal string data within that object. 它返回一个字符串对象,然后获得一个指向该对象内部字符串数据的指针。 The string then goes out of scope at the end of that line so you are left with a pointer to ... whatever happens to be in that memory next. 然后,该字符串在该行的末尾超出范围,因此您将得到一个指向...的指针……接下来该内存中的任何内容。

static std::string str = tmp_s.str();
static const char* post_data1 = str.c_str();

Might work for you. 可能会为您工作。

Try to delete the static storage specifiers, compile and run. 尝试删除static存储说明符,进行编译并运行。

NOTE: even though c_str() result is nominally temporary, it is may also be (and usually is) permanent. 注意:即使c_str()结果名义上是临时的,它也可能是(并且通常是)永久的。 For a quick fix, it may work. 快速修复,它可能会起作用。

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

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