Julien
Julien

Reputation: 1980

C++ Curl post dynamic var

I would like to use dynamic variables with POST curl
I use this code:

int send(const char*s)
{
  CURL *curl;
  CURLcode res;


  curl_global_init(CURL_GLOBAL_ALL);
  curl = curl_easy_init();
  if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/query.php");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "q=" + s);
    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);
  }
  curl_global_cleanup();
  std::cout << std::endl << "Query sent" << std::endl;
  return 0;
}

And i get this error:

test.cpp:199:57: error: invalid operands of types ‘const char [3]’ and ‘const char*’ to binary ‘operator+’
         curl_easy_setopt(curl, CURLOPT_POSTFIELDS, "q=" + s);
                                                    ~~~~~^~~

Upvotes: 0

Views: 238

Answers (1)

rafix07
rafix07

Reputation: 20934

You have to concatenate "q=" and s by yourself, there is no operator + in Cpp which concatenates chars array with pointer to chars. Create string with "q=", add data pointed by s to this string and call c_str() to get const char* pointer as parameter of curl_easy_setopt function:

#include <string>
....
curl_easy_setopt(curl, CURLOPT_URL, "http://localhost/query.php");
std::string buf("q=");
buf += s;
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, buf.c_str());

Upvotes: 2

Related Questions