parent
1018c6b000
commit
7586d211ac
@ -0,0 +1,89 @@
|
|||||||
|
#include <iostream>
|
||||||
|
#include <fstream>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
using namespace std;
|
||||||
|
|
||||||
|
struct WeatherData
|
||||||
|
{
|
||||||
|
string cityName;
|
||||||
|
int temperature;
|
||||||
|
int humidity;
|
||||||
|
int windSpeed;
|
||||||
|
};
|
||||||
|
bool readWeatherData(const string& filename, vector<WeatherData>& data)
|
||||||
|
{
|
||||||
|
ifstream File;
|
||||||
|
File.open(filename);
|
||||||
|
|
||||||
|
|
||||||
|
if(File.is_open())
|
||||||
|
{
|
||||||
|
string line;
|
||||||
|
char ws;
|
||||||
|
while (getline(File, line))
|
||||||
|
{
|
||||||
|
istringstream iss(line);
|
||||||
|
WeatherData weather;
|
||||||
|
|
||||||
|
if (getline(iss, weather.cityName, ',') &&
|
||||||
|
(iss >> weather.temperature >> ws >> weather.humidity >> ws >> weather.windSpeed))
|
||||||
|
{
|
||||||
|
data.push_back(weather);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
cout << "无法打开文件 " << filename << endl;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
File.close();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void findAndDisplayWeather(const string& cityName, const vector<WeatherData>& data)
|
||||||
|
{
|
||||||
|
bool found = false;
|
||||||
|
for (const auto& weather : data)
|
||||||
|
{
|
||||||
|
if (weather.cityName == cityName)
|
||||||
|
{
|
||||||
|
found = true;
|
||||||
|
cout << cityName << "的天气数据为:温度" << weather.temperature
|
||||||
|
<< ", 湿度" << weather.humidity
|
||||||
|
<< ", 风速" << weather.windSpeed << endl;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!found)
|
||||||
|
{
|
||||||
|
cout << "未找到城市 " << cityName << " 的天气数据。" << endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int main()
|
||||||
|
{
|
||||||
|
string filename;
|
||||||
|
cout << "请输入文件名:";
|
||||||
|
cin >> filename;
|
||||||
|
|
||||||
|
string cityName;
|
||||||
|
cout << "请输入要检索的城市名:";
|
||||||
|
cin >> cityName;
|
||||||
|
|
||||||
|
vector<WeatherData> weatherData;
|
||||||
|
if (!readWeatherData(filename, weatherData))
|
||||||
|
{
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
findAndDisplayWeather(cityName, weatherData);
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
Loading…
Reference in new issue