Skip to content

C Plus Plus Example Code

MMDRZA edited this page Oct 18, 2024 · 1 revision
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>

// Function to handle data received by curl
size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* s) {
    s->append(static_cast<char*>(contents), size * nmemb);
    return size * nmemb;
}

// Function to fetch and display cryptocurrency data
void fetchCryptoData() {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl = curl_easy_init();
    if (curl) {
        // Set URL
        curl_easy_setopt(curl, CURLOPT_URL, "https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json");
        // Set callback function to write data
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        // Perform request
        res = curl_easy_perform(curl);
        // Check if the request was successful
        if (res != CURLE_OK) {
            std::cerr << "Failed to fetch data: " << curl_easy_strerror(res) << std::endl;
        } else {
            // Parse JSON using nlohmann::json
            auto jsonData = nlohmann::json::parse(readBuffer);

            // Loop through and display each coin's information
            for (const auto& coin : jsonData) {
                std::string symbol = coin["symbol"];
                std::string lastPrice = coin["lastPrice"];
                std::string highPrice24h = coin["highPrice24h"];
                std::string lowPrice24h = coin["lowPrice24h"];
                std::string changeRate = coin["changeRate"];
                std::string lastUpdated = coin["lastUpdated"];

                std::cout << "Symbol: " << symbol << " | LAST: " << lastPrice
                          << " | HIGH: " << highPrice24h << " | LOW: " << lowPrice24h
                          << " | CHANGE: " << changeRate << " | UPDATED: " << lastUpdated << std::endl;
            }
        }
        curl_easy_cleanup(curl);
    }
}

int main() {
    fetchCryptoData();
    return 0;
}

Compile and Run

Install Dependencies: You need to have libcurl and the nlohmann/json library installed.

g++ -o crypto_fetcher crypto_fetcher.cpp -lcurl -std=c++11
./crypto_fetcher
Clone this wiki locally