【发布时间】:2016-02-17 04:32:31
【问题描述】:
这是我在 stackoverflow 中的第一个问题。我目前正在通过仅使用字符串和向量以及 fstream 来读取文本文件中的整体统计信息。
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
struct weather{
string year,month,sky,mintemp,maxtemp,totrain,y, date;
int rain = 0,scatter = 0,partly = 0,fog = 0,clean = 0,snow = 0, most = 0,storm = 0,cast = 0;
};
int main(){
string year;
int entry = 0;
vector<weather>vw;
weather w;
ifstream w_file;
w_file.open("weather.txt");
while (w_file >> w.date >> w.sky >> w.mintemp >> w.maxtemp >> w.totrain){
year = w.date.substr(0,4);
cout << year << endl;
}
cout << entry ; //this was just to confirm how many line i have in the file
我设法打印出的是文件的年份。我想要做的是读取特定年份的数据并打印出特定年份及其内容。无论如何我可以在不使用 goto 的情况下做到这一点吗?
数据文件
2012-01-01 Rain 7 13 0.28
2012-01-02 ScatteredClouds 4 8 0.25
2012-01-03 Rain 6 12 0.28
2012-01-04 Rain 5 10 0.28
2012-01-05 Rain 7 12 0.28
2012-01-06 PartlyCloudy 3 9 0.28
2012-01-07 PartlyCloudy 7 11 0.25
2012-01-08 Rain 7 10 0.28
2012-01-09 PartlyCloudy 6 12 0.25
2013-01-01 Rain 3 8 0.28
2013-01-02 Rain 2 11 0.25
2013-01-03 PartlyCloudy 9 11 0.28
2013-01-04 PartlyCloudy 8 10 0.28
输出
year = 2012
rain = 0//rain++ if rain is found
partlyCloudy = 0//partly++ if partlyCloudy is found
year = 2013
rain = 0//rain++ if rain is found
partlyCloudy = 0//partly++ if partlyCloudy is found
【问题讨论】:
-
我发布的正确吗?
-
你能把weather.txt的格式或示例内容贴出来吗?
-
当然。 2012-01-01 雨 7 13 0.28 2012-01-02 散云 4 8 0.25 2012-01-03 雨 6 12 0.28 2012-01-04 雨 5 10 0.28 2012-01-05 雨 7 12 0.28 2012-01-06多云 3 9 0.28 2012-01-07 多云 7 11 0.25 2012-01-08 雨 7 10 0.28 2012-01-09 多云 6 12 0.25
-
很抱歉,如果它看起来很乱,我显然不知道如何发布它