繁体   English   中英

字符串转换为const char *问题

[英]string conversion to const char * problems

我有这个问题,每当我尝试通过libcurls http发送我的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);

当您使用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 )可能是最安全的选择。

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

是个问题。 它返回一个字符串对象,然后获得一个指向该对象内部字符串数据的指针。 然后,该字符串在该行的末尾超出范围,因此您将得到一个指向...的指针……接下来该内存中的任何内容。

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

可能会为您工作。

尝试删除static存储说明符,进行编译并运行。

注意:即使c_str()结果名义上是临时的,它也可能是(并且通常是)永久的。 快速修复,它可能会起作用。

暂无
暂无

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

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