我正在撰寫一個從文本檔案中獲取變數并將其添加到固定 url 的 c 代碼,類似于以下示例:
int x = numbers[n];
string url = "http://example.com/" x;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
但我在編譯后收到此錯誤訊息
libcurl 中不支持或禁用協議“tp”
我該如何解決?
uj5u.com熱心網友回復:
int x = numbers[n];
string url = "http://example.com/" x;
在 c/c 中有指標演算法。
const char* ptr = "abcde";
string s1 = ptr 0; // "abcde";
string s2 = ptr 1; // "bcde";
string s3 = ptr 2; // "cde";
...
所以你的字串是錯誤的。
請在網上to_string()
查看const char* to string
。
uj5u.com熱心網友回復:
您正在向指標添加一個int
(const char*
從型別的字串文字衰減const char[20]
)。這將使指標偏移指示的元素int
數量。在您的情況下,這似乎是 2,這就是 CURL 認為 URL 以tp:
而不是 . 開頭的原因http:
。
您的代碼基本上是這樣的:
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
要解決此問題,您可以std::to_string()
在 C 11 及更高版本中使用將 轉換int
為 a string
,例如:
string url = "http://example.com/" to_string(x);
或者,您可以使用std::ostringstream
(在所有 C 版本中),例如:
ostringstream oss;
oss << "http://example.com/" << x;
string url = oss.str();
或者,您可以std::format()
在 C 20 及更高版本中使用(您可以在早期版本中使用{fmt} 庫),例如:
string url = format("http://example.com/{}", x);
// or:
string url = format("{}{}", "http://example.com/", x);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/515314.html
標籤:C 库库尔