首页 > 后端开发 > C++ > 正文

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

P粉602998670
发布: 2025-08-19 11:21:01
原创
527人浏览过
使用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:

立即学习C++免费学习笔记(深入)”;

  • 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(单头文件,易集成)。

网易天音
网易天音

网易出品!一站式音乐创作工具!零基础写歌!

网易天音 76
查看详情 网易天音

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库,就能实现一个基础但完整的天气查询程序。后续可扩展支持命令行输入城市、多城市查询、定时更新等功能。

以上就是C++天气查询程序 网络API调用与解析的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号