为什么我不能将std :: string与libcurl一起使用?

时间:2013-10-10 18:38:06

标签: c++ string curl

我正在尝试创建一个非常简单的程序,请求几页,这是我的代码到目前为止:

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()来卷曲,但没有任何反应,只需跳过卷曲功能,打印网址并暂停。
如果我注释掉thar行,并取消注释“char const chFUrl [] ...”,一切正常并且卷曲输出到终端的html响应。

当我运行fUrl.c_str()并且它不起作用时,VS上的控制台上没有任何内容。我对C ++的经验很少,所以很感激任何想法。

- 编辑: 我刚刚测试了这段代码:

char const chFUrl[] = "http://google.com";
for (int i = 0; i < sizeof(chFUrl); i++) {
    cout << chFUrl[i] << endl;
}

然后,当我使用它时,它将整个网址输出到终端:

char const* chFUrl = fUrl.c_str();
for (int i = 0; i < sizeof(chFUrl); i++) {
    cout << chFUrl[i] << endl;
}

它只输出“http”,即使很难,如果我cout chFUrl [4]我得到“:”。

1 个答案:

答案 0 :(得分:0)

您的第三个代码段存在问题。 sizeof(chFUrl)将返回sizeof指针。它是const char*而不是const char数组。你应该用fUrl.size()代替它。