I'm working on a c code that fetches a variable from a text file and adds it to a fixed url, similarly to the following example:
int x = numbers[n];
string url = "http://example.com/" x;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
but I'm getting this error message after compiling
Protocol "tp" not supported or disabled in libcurl
How can I fix that?
CodePudding user response:
int x = numbers[n];
string url = "http://example.com/" x;
In c/c there is pointer arithmetic.
const char* ptr = "abcde";
string s1 = ptr 0; // "abcde";
string s2 = ptr 1; // "bcde";
string s3 = ptr 2; // "cde";
...
So your string is wrong.
Please check to_string()
and const char* to string
on web.
CodePudding user response:
You are adding an int
to a const char*
pointer (that was decayed from a string literal of type const char[20]
). That will offset the pointer by however many elements the int
indicates. Which, in your case, appears to be 2, which is why CURL thinks the URL begins with tp:
instead of http:
.
Your code is basically the equivalent of this:
const char strliteral[] = "http://example.com/";
...
int x = numbers[n];
const char *p = strliteral;
string url = p x; // ie: &p[x]
h t t p : / / e x a m p l e . c o m /
^ ^
| |
p p 2
To fix that, you can use std::to_string()
in C 11 and later to convert the int
to a string
, eg:
string url = "http://example.com/" to_string(x);
Or, you can use a std::ostringstream
(in all C versions), eg:
ostringstream oss;
oss << "http://example.com/" << x;
string url = oss.str();
Or, you can use std::format()
in C 20 and later (you can use the {fmt} library in earlier versions), eg:
string url = format("http://example.com/{}", x);
// or:
string url = format("{}{}", "http://example.com/", x);