【C++进阶实战】基于linux的天气预报系统

项目结构

  1. main.cpp:主程序文件,负责用户交互和调用天气查询函数。
  2. weather_api.cpp:实现天气数据的获取和解析。
  3. weather_api.h:天气数据获取和解析的头文件。
  4. CMakeLists.txt:CMake配置文件,用于编译项目。

1. 安装依赖库

首先,你需要安装cURL库。在大多数Linux发行版中,你可以使用包管理器来安装:

复制代码
sudo apt-get install libcurl4-openssl-dev

在Windows上,你可以从cURL官方网站下载预编译的库文件。

2. 获取API密钥

注册并获取OpenWeatherMap API密钥。你可以在这里注册:OpenWeatherMap API

3. 项目文件

weather_api.h
复制代码
#ifndef WEATHER_API_H
#define WEATHER_API_H

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

class WeatherAPI {
public:
    WeatherAPI(const std::string& apiKey);
    std::string getWeather(const std::string& city);

private:
    std::string apiKey;
};

#endif // WEATHER_API_H
weather_api.cpp
复制代码
#include "weather_api.h"
#include <iostream>
#include <string>
#include <curl/curl.h>
#include <nlohmann/json.hpp>

using json = nlohmann::json;

size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* buffer) {
    size_t totalSize = size * nmemb;
    buffer->append((char*)contents, totalSize);
    return totalSize;
}

WeatherAPI::WeatherAPI(const std::string& apiKey) : apiKey(apiKey) {}

std::string WeatherAPI::getWeather(const std::string& city) {
    CURL* curl;
    CURLcode res;
    std::string readBuffer;

    curl_global_init(CURL_GLOBAL_DEFAULT);
    curl = curl_easy_init();

    if (curl) {
        std::string url = "http://api.openweathermap.org/data/2.5/weather?q=" + city + "&appid=" + apiKey + "&units=metric";
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
        res = curl_easy_perform(curl);

        if (res != CURLE_OK) {
            std::cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << std::endl;
        }

        curl_easy_cleanup(curl);
    }

    curl_global_cleanup();

    return readBuffer;
}
main.cpp
复制代码
#include <iostream>
#include <string>
#include "weather_api.h"
#include <nlohmann/json.hpp>

using json = nlohmann::json;

void displayWeather(const std::string& response) {
    try {
        json j = json::parse(response);
        std::string city = j["name"];
        std::string country = j["sys"]["country"];
        double temperature = j["main"]["temp"];
        std::string description = j["weather"][0]["description"];
        double humidity = j["main"]["humidity"];
        double windSpeed = j["wind"]["speed"];

        std::cout << "Weather in " << city << ", " << country << ":" << std::endl;
        std::cout << "Temperature: " << temperature << " °C" << std::endl;
        std::cout << "Description: " << description << std::endl;
        std::cout << "Humidity: " << humidity << "%" << std::endl;
        std::cout << "Wind Speed: " << windSpeed << " m/s" << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Error parsing JSON: " << e.what() << std::endl;
    }
}

int main() {
    std::string apiKey = "YOUR_API_KEY_HERE"; // 替换为你的API密钥
    WeatherAPI api(apiKey);

    std::string city;
    std::cout << "Enter the city name: ";
    std::getline(std::cin, city);

    std::string response = api.getWeather(city);
    displayWeather(response);

    return 0;
}
CMakeLists.txt
复制代码
cmake_minimum_required(VERSION 3.10)
project(SimpleWeatherApp)

set(CMAKE_CXX_STANDARD 17)

find_package(CURL REQUIRED)
include_directories(${CURL_INCLUDE_DIRS})

add_executable(SimpleWeatherApp main.cpp weather_api.cpp)

target_link_libraries(SimpleWeatherApp ${CURL_LIBRARIES})

4. 编译和运行

  1. 创建一个项目目录并导航到该目录。

  2. 创建上述文件并保存。

  3. 在项目目录中创建一个build目录并进入该目录:

    复制代码
    mkdir build
    cd build
  4. 运行CMake生成Makefile:

    复制代码
    cmake ..
  5. 编译项目:

    复制代码
    make
  6. 运行程序:

    复制代码
    ./SimpleWeatherApp

5. 运行示例

运行程序后,输入一个城市名,程序将显示该城市的天气信息。

注意事项

  • 确保你的API密钥是有效的。
  • 如果你在编译过程中遇到问题,检查是否正确安装了所有依赖库。
  • 你可以根据需要扩展功能,例如添加更多的天气信息显示、错误处理等。
相关推荐
Ravikov2 分钟前
工具开发-ESP32程序管理系统 | 具体实现(一)
c++
名字还没想好☜4 分钟前
Next.js Route Handler 做 SSE 服务端推送:实时进度条、自动重连与什么时候别用 WebSocket
开发语言·javascript·websocket·react·sse·next.js
进制树6 分钟前
【飞控开发实战·㉒】ROS2无人机应用开发实战:Offboard控制、航点任务、AprilTag降落与避障系统
开发语言·安全·无人机·课程设计
江畔柳前堤16 分钟前
LLM + Agent 模型效果评估:从入门到工业级体系构建的完整指南
开发语言·人工智能·自然语言处理·chatgpt·架构·json·batch
路多辛20 分钟前
一个 Go 写的全能 AI Agent,讲讲 covo-agent
java·开发语言·golang
欧特克_Glodon1 小时前
OpenCV计算机视觉开发入门与实践<十六>:图像边框和图像轮廓
c++·人工智能·opencv·计算机视觉
wuminyu1 小时前
JDK21中FFM api的upcall回调机制解析
java·linux·c语言·jvm·c++
格林威1 小时前
C#图像处理:使用imagemagick实现像素放大水印转换等多种功能
android·开发语言·图像处理·人工智能·计算机视觉·c#·视觉检测
wifi___6 小时前
全局异常处理的原理
java·开发语言
我变成萤火虫8 小时前
河南萌新联赛2026第(四)场:南阳理工学院
数据结构·c++·算法·贪心算法·stl·动态规划