【C++进阶实战】基于linux的天气预报系统
项目结构
- main.cpp:主程序文件,负责用户交互和调用天气查询函数。
- weather_api.cpp:实现天气数据的获取和解析。
- weather_api.h:天气数据获取和解析的头文件。
- 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. 编译和运行
- 创建一个项目目录并导航到该目录。
- 创建上述文件并保存。
- 在项目目录中创建一个
build
目录并进入该目录:mkdir build cd build
- 运行CMake生成Makefile:
cmake ..
- 编译项目:
make
- 运行程序:
./SimpleWeatherApp
5. 运行示例
运行程序后,输入一个城市名,程序将显示该城市的天气信息。
注意事项
- 确保你的API密钥是有效的。
- 如果你在编译过程中遇到问题,检查是否正确安装了所有依赖库。
- 你可以根据需要扩展功能,例如添加更多的天气信息显示、错误处理等。