在 C++ 中使用 URL 从数组中插入字符串以使用 libcurl 执行 GET 请求

Interpolating string from array with URL in C++ to perform GET request using libcurl

我正在尝试使用与每个名称对应的 URL 对五个不同的名称发出 GET 请求,但是 Xcode 一直在 curl_easy_setopt(curl, CURLOPT_URL, namesURL); 行旁边告诉我它 Cannot pass object of non-trivial type 'std::__1::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >') through variadic function; call will abort at runtime.

是不是我的字符串插值有问题导致了这个问题?我尝试使用 cout << typeid(stockURL).name() << endl; 查看我正在使用的数据类型,但我不明白我得到的结果。

    int main(){
        string names[5] = {"Joe", "Suzy", "Larry", "Sally", "John"};
        for(int i = 0; i < 5;i++){
          string namesURL = "http://names.com/" + names[i];
          cout << url << endl;


          CURL *curl;
          CURLcode res;

          curl = curl_easy_init();
          if(curl) {
              curl_easy_setopt(curl, CURLOPT_URL, namesURL);

              /* Perform the request, res will get the return code */
              res = curl_easy_perform(curl);
              /* Check for errors */
              if(res != CURLE_OK)
                fprintf(stderr, "curl_easy_perform() failed: %s\n",
                    curl_easy_strerror(res));

               /* always cleanup */
               curl_easy_cleanup(curl);
          }
        }
    }

Botje 在评论中回答了我的问题,指出通过传递 namesURL.c_str() 可以获得常规 const char * 而不是 std::string.

有关 c_str() 的使用参考,请查看 this SO post