gpt4 book ai didi

c++ - 将 CURL 转换为字符串时为空值

转载 作者:行者123 更新时间:2023-11-28 05:08:32 24 4
gpt4 key购买 nike

我想获取页面的源代码,我有这个函数来填充一个字符串。

我的头文件:

class Explorateur {
public:
Explorateur();
~Explorateur();
std::string RecupererCodeSource(std::string pAdresse);

static size_t WriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{
((std::string*)userp)->append((char*)contents, size * nmemb);
return size * nmemb;
}

};

我的类(class)文件:

std::string Explorateur::RecupererCodeSource(std::string pAdresse)
{
CURL *curl;
CURLcode res;
std::string readBuffer;

curl = curl_easy_init();
if(curl)
{
curl_easy_setopt(curl, CURLOPT_URL, pAdresse);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
std::cout << "curl : " << curl << std::endl;
res = curl_easy_perform(curl);
std::cout << "res : " << res << std::endl;
curl_easy_cleanup(curl);

}
std::cout << "Read : " << readBuffer << std::endl;
return readBuffer;
}

我的主要:

int main()
{
Explorateur explorateur;
std::string valeur = explorateur.RecupererCodeSource("https://www.google.com/");
return 0;
}

结果没有异常(exception),它是空的,你知道为什么吗?

curl  : 0x1450d60
res : 6
Read :

最佳答案

作为 C 库的 Lib Curl 遵循旧的“良好”可变参数设计。这就是为什么您的代码在编译时会做完全出乎意料的事情。

拥有

CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...) 

这在你的代码中

curl_easy_setopt(curl, CURLOPT_URL, pAdresse);

产生您正在目睹的行为。

改变你的代码

curl_easy_setopt(curl, CURLOPT_URL, pAdresse.c_str());

如果你使用 C++ 甚至更好 >= 11

curl_easy_setopt(curl, CURLOPT_URL, pAdresse.data());

而且它还活着))。

关于c++ - 将 CURL 转换为字符串时为空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44034527/

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