LibCurl CURLOPT_URL不接受字符串?C++

Som*_*Guy 4 c++ syntax-error libcurl

基本上我想要做的是使用libcurl来获取稍微不同的URL,例如:

http://foo.com/foo.asp?name=*NAMEHERE*
Run Code Online (Sandbox Code Playgroud)

我想做的是遍历名称向量并获取每个名称,例如:

http://foo.com/foo.asp?name=James
Run Code Online (Sandbox Code Playgroud)

然后

http://foo.com/foo.asp?name=Andrew
Run Code Online (Sandbox Code Playgroud)

等等.

但是,当我尝试这样做时:

int foo (){
    CURL *curl;
    CURLcode success;
    char errbuf[CURL_ERROR_SIZE];
    int m_timeout = 15;

    if ((curl = curl_easy_init()) == NULL) {
        perror("curl_easy_init");
        return 1;
    }

    std::vector<std::string> names;

    names.push_back("James");
    names.push_back("Andrew");

    for (std::vector<std::string>::const_iterator i = names.begin(); i != names.end(); ++i){
        curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errbuf);
        curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);

        curl_easy_setopt(curl, CURLOPT_TIMEOUT, long(m_timeout));
        curl_easy_setopt(curl, CURLOPT_URL, "http://foo.com/foo.asp?name=" + *i);
        curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt");
        curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");
        curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
        curl_easy_setopt(curl, CURLOPT_AUTOREFERER, 1L);
    }

    if ((success = curl_easy_perform(curl)) != 0) {
        fprintf(stderr, "%s: %s\n", "curl_easy_perform", errbuf);
        return 1;
    }

    curl_easy_cleanup(curl);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它给了我一个错误:

无法通过可变参数函数传递非平凡类型'std :: __ 1 :: basic_string <char>'的对象; call将在运行时中止

在这一行:

curl_easy_setopt(curl, CURLOPT_URL, "http://foo.com/foo.asp?name=" + *i);
Run Code Online (Sandbox Code Playgroud)

因为+ *i.

我想做什么?有解决方案吗?

编辑:谢谢你的答案,但由于某种原因,当我运行它时,它只获得带有向量中最后一个字符串的网站,而忽略了其他的.就我而言,它会跳过James并直接进入Andrew.为什么会这样?

jho*_*n0x 10

传递给curl_easy_setoptfor 的参数CURLOPT_URL需要是a char *而不是a std::string.你可以得到一个const char *std::string通过调用其c_str成员函数:

std::string url = "http://foo.com/foo.asp?name=" + *i;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
Run Code Online (Sandbox Code Playgroud)

对于将来会在这里结束的任何人,如果您还没有,请查看卷曲手册.还有一本在线书籍.

curl_easy_setopt的文档说您需要阅读有关特定选项的信息,以了解要使用的参数类型.

所有选项都使用选项后跟参数进行设置.该参数可以是long,函数指针,对象指针或curl_off_t,具体取决于特定选项所期望的内容.请仔细阅读本手册,因为错误的输入值可能导致libcurl表现不佳!

CURLOPT_URL的文档确切地说明了参数类型需要的内容.

传入指向要使用的URL的指针.该参数应为char*到零终止字符串,该字符串必须采用以下格式进行URL编码:

方案://主机:端口/路径