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

想用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#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(单头文件,易集成)。
本书以培养高级网站建设与管理人才为目标,内容循序渐进,由浅入深,通过大量的实例系统全面地介绍了Linux+PHP+MySQL环境下的网络后台开发技术。本书详尽分析了近30个典型案例。包括计数器、网站流量统计、留言板、论坛系统、聊天室、投票与调查、用户管理、新闻发布系统、广告轮播、购物系统等等,力求让读者通过对案例的学习,轻松掌握PHP和MySQL的编程精要,迅速掌握网络后台开发技巧。 本书适
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库,就能实现一个基础但完整的天气查询程序。后续可扩展支持命令行输入城市、多城市查询、定时更新等功能。









