Search code examples
c++getlibcurlstring-interpolation

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


I am trying to make a GET request for five different names using URLs that correspond to each name, but Xcode keeps telling me beside the line that says curl_easy_setopt(curl, CURLOPT_URL, namesURL); that it 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.

Is there a problem with my string interpolation that is causing this problem? I have tried to use cout << typeid(stockURL).name() << endl; to see what data types I am working with, but I don't understand the results I am getting.

    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);
          }
        }
    }

Solution

  • Botje answered my question in the comments, pointing out that by passing namesURL.c_str() it is possible to get a regular const char * instead of a std::string.

    For reference on the use of c_str(), check out this SO post.