cplusplus
cplusplus

 

Introduction

This program demonstrates how to fetch and display weather information using an API in the C++ programming language.
The weather data is retrieved from a public API, such as the OpenWeatherMap API, which provides detailed weather information for any given location.
We will use the libcurl library to make HTTP requests to the API and retrieve the data in JSON format. The program will parse the JSON response and display the weather information in a readable format.

Objective

The objective of this program is to:

  • Make an HTTP request to a weather API using C++.
  • Parse the JSON response from the API.
  • Display the weather information to the user in a readable format.

C++ Code to Fetch and Display Weather Information

#include <iostream>
#include <string>
#include <curl/curl.h>
#include <json/json.h>

using namespace std;

// Function to write the response data
size_t WriteCallback(void *contents, size_t size, size_t nmemb, string *output) {
    size_t totalSize = size * nmemb;
    output->append((char*)contents, totalSize);
    return totalSize;
}

int main() {
    CURL *curl;
    CURLcode res;
    string readBuffer;
    string apiKey = "YOUR_API_KEY"; // Replace with your OpenWeatherMap API key
    string city = "London";  // Replace with desired city
    string url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey;

    // Initialize curl
    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if(curl) {
        // Set URL for the request
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

        // Set the callback function to handle the response
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        // Make the request
        res = curl_easy_perform(curl);

        if(res != CURLE_OK) {
            cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
        } else {
            // Parse the JSON response
            Json::Reader reader;
            Json::Value obj;
            reader.parse(readBuffer, obj);

            // Extract weather information
            string cityName = obj["name"].asString();
            string weatherDescription = obj["weather"][0]["description"].asString();
            double temperature = obj["main"]["temp"].asDouble() - 273.15; // Convert from Kelvin to Celsius

            // Display the weather information
            cout << "Weather information for " << cityName << ":\n";
            cout << "Description: " << weatherDescription << endl;
            cout << "Temperature: " << temperature << " °C" << endl;
        }

        // Cleanup
        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();
    return 0;
}

Program Explanation

The program starts by including the necessary libraries. The libcurl library is used to make HTTP requests, and the jsoncpp library is used to parse the JSON response.

The WriteCallback function is responsible for storing the response data in a string as it is received from the server.

In the main() function, the URL for the OpenWeatherMap API is constructed using the city name and API key. The API key can be obtained by signing up on the OpenWeatherMap website.

After making the request, the program parses the JSON response to extract the weather description and temperature. The temperature is converted from Kelvin to Celsius.

How to Run the Program

To run this program on your system, follow these steps:

  • Ensure you have the libcurl and jsoncpp libraries installed on your system.
  • Replace the YOUR_API_KEY with your actual OpenWeatherMap API key.
  • Compile the program using a C++ compiler with the appropriate flags to link the libcurl and jsoncpp libraries. For example:
g++ -o weatherFetcher weatherFetcher.cpp -lcurl -ljsoncpp
  • Run the compiled program:
./weatherFetcher

The program will then display the weather information for the specified city.

 

© 2024 Learn Programming

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)