- Notifications
You must be signed in to change notification settings - Fork 0
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 curlsize_tWriteCallback(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 datavoidfetchCryptoData(){CURL* curl; CURLcode res; std::string readBuffer; curl = curl_easy_init(); if (curl){// Set URLcurl_easy_setopt(curl, CURLOPT_URL, "https://raw.githubusercontent.com/Crypto-Static/Rate/main/rateStatic.json"); // Set callback function to write datacurl_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 successfulif (res != CURLE_OK){std::cerr << "Failed to fetch data: " << curl_easy_strerror(res) << std::endl} else{// Parse JSON using nlohmann::jsonauto jsonData = nlohmann::json::parse(readBuffer); // Loop through and display each coin's informationfor (constauto& 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)} } intmain(){fetchCryptoData(); return0} 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👨💻 Programmer : PyMmdrza 🌍 Official Website Mmdrza.Com 📧 Email : Pymmdrza@gmail.com 📧 first@programmer.net