字符串转换为const char*问题

1 c++ string const char libcurl

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

任何人都可以告诉我为什么当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);
Run Code Online (Sandbox Code Playgroud)

Som*_*ude 7

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

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

// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, post_data.c_str());
Run Code Online (Sandbox Code Playgroud)

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

// Post the data
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, tmp_s.str().c_str());
Run Code Online (Sandbox Code Playgroud)

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