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

标签 c++ string char constants libcurl

我有这个问题,每当我尝试通过 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/

相关文章:

c - fgetc 返回一个奇怪的字符

c# - 如何在不复制的情况下从 char 数组创建字符串?

c++ - 有人可以解释一下这段代码中使用 BaseTypeX::BaseTypeX 吗?

c++ - volatile sig_atomic_t 的内存安全

c++ - C++ 中的函数范围异常处理——这是一种糟糕的风格吗?

c++ - 当我们尝试使用 istream::getline() 和 std::getline() 提取文件中出现 `eof` 字符的行时,实际会发生什么

c++ - 如何找到字符串中子字符串的所有位置?

java - 测试 toString 但失败?

c++ - 通过多线程程序 (C++) 打印 {0, 1, 2, 3} 的排列

c - 在标准 C 中从头开始实现 memcpy 在技术上是不可能的吗?