【发布时间】:2013-10-10 18:38:05
【问题描述】:
我正在尝试制作一个请求几页的非常简单的程序,到目前为止,这是我的代码:
string fUrl = "http://google.com/";
int main(int argc, char *argv[]) {
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if (curl) {
char const* chFUrl = fUrl.c_str();
//char const chFUrl[] = "http://google.com/";
curl_easy_setopt(curl, CURLOPT_URL, chFUrl);
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
res = curl_easy_perform(curl);
if (res != CURLE_OK)
fprintf(stderr, "curl_easy_perform() failed: %s\n",
curl_easy_strerror(res));
curl_easy_cleanup(curl);
cout << chFUrl << endl;
system("pause");
}
return 0;
}
现在,请注意我正在尝试将 fUrl.c_str() 传递给 curl,但没有任何反应,它只是跳过 curl 函数,打印 url 并暂停。
如果我注释掉 thar 行,并取消注释“char const chFUrl[]...”,一切正常,并且 curl 将 html 响应输出到终端。
当我运行 fUrl.c_str() 并且它不起作用时,VS 上的控制台不会打印任何内容。我对 C++ 的经验很少,因此欢迎任何想法。
--编辑: 我刚刚测试了这段代码:
char const chFUrl[] = "http://google.com";
for (int i = 0; i < sizeof(chFUrl); i++) {
cout << chFUrl[i] << endl;
}
它会将整个 url 输出到终端,但是,当我使用它时:
char const* chFUrl = fUrl.c_str();
for (int i = 0; i < sizeof(chFUrl); i++) {
cout << chFUrl[i] << endl;
}
它只输出“http”,即使我 cout chFUrl[4] 我得到“:”也很难。
【问题讨论】:
-
你试过在
main里面声明和初始化fUrl吗? -
查看this documentation 它说
curl_easy_setopt()的第三个参数“可以是long、函数指针、对象指针或curl_off_t”。您正在传递一个字符串。会不会是个问题? -
请提供完整示例程序,以便我们重现您的结果。请参阅SSCCE.ORG 了解更多信息。
-
我无法重现您的问题。例如,This program 在 Ubuntu 13.04 上非常适合我。也就是说,当我运行它时,它会显示谷歌首页的内容。