gpt4 book ai didi

c++ - 字符串转换为 const char * 问题

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:17 24 4
gpt4 key购买 nike

我有这个问题,每当我尝试通过 libcurls http post 发送我的 post_data1 时,它说密码错误,但是当我在 post_data2 中使用固定表达式时,它会登录。当我 cout 时,它们是完全相同的字符串。 .

谁能告诉我为什么当 libcurl 将它们放在标题中时它们不一样?或者如果是这样的话,为什么在我发送它们之前它们会有所不同。

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);

最佳答案

当您使用 tmp_s.str() 时,您会得到一个临时 字符串。您不能保存指向它的指针。您必须将其保存到 std::string 并在调用中使用该字符串:

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

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

如果(且仅当)curl_easy_setopt 复制 字符串(而不是仅保存指针),您可以在调用中使用 tmp_s :

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

但我不知道该函数是复制字符串还是只保存指针,因此第一种选择(使用 std::string)可能是最安全的选择。

关于c++ - 字符串转换为 const char * 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15155277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com