我一直在 C 中使用 cURL 庫來發出 HTTP 請求。將結果存盤在字串中時,它作業得很好,但是結果是這樣的:

這都是一個連續的字串。我想訪問每個匯率并將它們保存到不同的變數中,以便我可以用它們進行計算。我嘗試將它保存到 amap而不是 astring中,并且它可以編譯,但是在運行它時會中止并且不清楚原因。
給我問題的代碼在這里:
#define CURL_STATICLIB
#include "curl/curl.h"
#include <iostream>
#include <string>
#include <map>
// change cURL library depending on debug or release config
#ifdef _DEBUG
#pragma comment(lib, "curl/libcurl_a_debug.lib")
#else
#pragma comment (lib, "curl/libcurl_a.lib")
#endif
// extra required libraries
#pragma comment (lib, "Normaliz.lib")
#pragma comment (lib, "Ws2_32.lib")
#pragma comment (lib, "Wldap32.lib")
#pragma comment (lib, "Crypt32.lib")
#pragma comment (lib, "advapi32.lib")
static size_t my_write(void* buffer, size_t size, size_t nmemb, void* param)
{
std::string& text = *static_cast<std::string*>(param);
size_t totalsize = size * nmemb;
text.append(static_cast<char*>(buffer), totalsize);
return totalsize;
}
int main()
{
// create var to store result from request
std::map<std::string, double> result;
CURL* curl;
CURLcode res;
curl_global_init(CURL_GLOBAL_DEFAULT);
curl = curl_easy_init();
if (curl) {
// determine the setup options for the request
curl_easy_setopt(curl, CURLOPT_URL, "http://api.exchangeratesapi.io/v1/latest?access_key=9c6c5fc6ca81e2411e4058311eafdf3b&symbols=USD,GBP,AUD&format=1");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, my_write);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &result);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
// perform the http request
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
if (CURLE_OK != res) {
std::cerr << "CURL error: " << res << '\n';
}
}
curl_global_cleanup();
std::map <std::string, double> ::const_iterator i;
for (i = result.begin(); i != result.end(); i )
{
std::cout << i->first << ": " << i->second;
}
}
要將其保存到字串中,我替換:
std::map<std::string, double> result;
并std::string result;替換:
std::map <std::string, double> ::const_iterator i;
for (i = result.begin(); i != result.end(); i )
{
std::cout << i->first << ": " << i->second;
}
與std::cout << result << "\n\n";.
通過這些替換,它運行良好,但它不是我需要的格式,除非可以從字串格式中提取特定值?
我覺得我正在嘗試做的事情非常具體,而且我一直在努力在網上找到任何可以幫助我的東西。
uj5u.com熱心網友回復:
您正在獲取一個 JSON(JavaScript 物件表示法)檔案。為了讓你的生活更輕松,你應該考慮使用一個庫來處理 C 中的 JSON,比如jsoncpp。這個網站在這里提供了一個快速教程。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/448098.html
