商城首页欢迎来到中国正版软件门户

您的位置:首页 >C++天气查询程序实现方法

C++天气查询程序实现方法

  发布于2025-08-26 阅读(0)

扫一扫,手机访问

使用C++通过OpenWeatherMap API实现天气查询,先用libcurl发送HTTP请求获取JSON数据,再用nlohmann/json库解析出城市、天气、温度、湿度和风速等信息并输出。

C++天气查询程序 网络API调用与解析

想用C++做一个天气查询程序,核心在于调用网络API并解析返回的数据。通常这类API返回的是JSON格式数据,我们需要通过HTTP请求获取,并在程序中解析出温度、天气状况、风速等信息。

选择合适的天气API

市面上有多个提供免费额度的天气API,适合学习和小项目使用:

  • OpenWeatherMap:注册后获取API Key,支持城市名、经纬度查询,返回JSON数据。
  • WeatherAPI:功能丰富,文档清晰,支持多语言。
  • 心知天气(国内):中文支持好,响应快,适合中文用户。

以OpenWeatherMap为例,查询城市的URL格式为:

http://api.openweathermap.org/data/2.5/weather?q=Beijing&appid=YOUR_API_KEY&units=metric

使用cURL发送HTTP请求

C++标准库不直接支持网络请求,常用libcurl来实现。先安装libcurl:

  • Ubuntu: sudo apt-get install libcurl4-openssl-dev
  • Windows: 使用vcpkg或手动下载编译

示例代码:用cURL获取API响应

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

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

std::string fetchWeatherData(const std::string& url) {
  CURL* curl;
  CURLcode res;
  std::string readBuffer;

  curl = curl_easy_init();
  if (curl) {
    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);
    curl_easy_cleanup(curl);

    if (res != CURLE_OK) {
      return "";
    }
  }
  return readBuffer;
}

解析JSON响应

API返回的是JSON字符串,需解析结构化数据。推荐使用轻量库 nlohmann/json(单头文件,易集成)。

GitHub地址:https://github.com/nlohmann/json

将json.hpp放入项目目录,包含即可使用。

#include "json.hpp"
using json = nlohmann::json;

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

    std::cout << "城市: " << city << "\n";
    std::cout << "天气: " << weather << "\n";
    std::cout << "温度: " << temp << "°C\n";
    std::cout << "湿度: " << humidity << "%\n";
    std::cout << "风速: " << windSpeed << " m/s\n";
  } catch (json::exception& e) {
    std::cerr << "解析失败: " << e.what() << "\n";
  }
}

整合与调用

主函数中组合请求与解析:

int main() {
  std::string apiKey = "YOUR_API_KEY";
  std::string city = "Shanghai";
  std::string url = "http://api.openweathermap.org/data/2.5/weather?q=" + city +
               "&appid=" + apiKey + "&units=metric";

  auto response = fetchWeatherData(url);
  if (response.empty()) {
    std::cout << "请求失败,请检查网络或API Key\n";
    return 1;
  }

  parseWeather(response);
  return 0;
}

编译时需链接cURL库:

g++ main.cpp -lcurl -o weather

基本上就这些。只要配置好API Key、引入cURL和JSON库,就能实现一个基础但完整的天气查询程序。后续可扩展支持命令行输入城市、多城市查询、定时更新等功能。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注