I've been using cURL library in C to make HTTP requests. When storing the result in a string it works perfectly fine however the result is like this:
and this is all one continuous string. I want to access each exchange rate and save them into different variables so I can make calculations with them. I have tried saving it into a map
instead of a string
, and it compiles, but when running it aborts and it's not clear why.
The code giving me problems is here:
#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;
}
}
To save it into a string, I replace:
std::map<std::string, double> result;
with std::string result;
and also replace:
std::map <std::string, double> ::const_iterator i;
for (i = result.begin(); i != result.end(); i )
{
std::cout << i->first << ": " << i->second;
}
with std::cout << result << "\n\n";
.
With these replacements, it runs fine, but it's just not in the format I need it in, unless it's possible to extract the particular values from the string format?
I get the feeling that what I'm trying to do is very specific and I've struggled to find anything online that can help me.
CodePudding user response:
You are grabbing a JSON (JavaScript Object Notation) file. To make your life much easier you should look into using a library for processing JSON in C like jsoncpp. This site here provides a quick tutorial.