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

使用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-devWindows: 使用vcpkg或手动下载编译

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

#include
#include

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     std::cout     std::cout     std::cout     std::cout   } catch (json::exception& e) {
    std::cerr   }
}

整合与调用

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

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     return 1;
  }

  parseWeather(response);
  return 0;
}

编译时需链接cURL库:

g++ main.cpp -lcurl -o weather

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1471929.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
怎样用C++实现文件加密程序 基础加密算法与文件流操作
上一篇 2025年12月18日 19:12:51
C++工厂模式实现 简单工厂方法示例
下一篇 2025年12月18日 19:13:01

相关推荐

发表回复

登录后才能评论
关注微信