读取直到fstream中文本的某一行

时间:2016-02-17 04:32:31

标签: c++ fstream

这是我在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 

1 个答案:

答案 0 :(得分:0)

当然,有一种方法可以在不使用goto的情况下执行此操作。我想不出任何需要goto的情况。

查看迭代你的向量。一个很好的参考是http://www.cplusplus.com/reference/vector/vector/begin/

此处的代码段示例为:

#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;
  for (int i=1; i<=5; i++) myvector.push_back(i);

  std::cout << "myvector contains:";
  for (std::vector<int>::iterator it = myvector.begin() ; it != myvector.end(); ++it)
    std::cout << ' ' << *it;
  std::cout << '\n';

  return 0;
}

在您的情况下,您需要检查每个*it是否匹配日期,然后如果日期匹配,则从相应的结构中输出您想要的数据。

或者,根据您要查找的具体日期的输入方式,您可以将其放入现有的while循环中,甚至不必将其他数据存储在vector中。在这种情况下,您的while循环可能类似于:

while (w_file >> w.date >> w.sky >> w.mintemp >> w.maxtemp >> w.totrain){
    year = w.date.substr(0,4);
    if (year == "1974") { // or whatever the year your looking for is...
    cout << w.date << w.sky << w.mintemp << w.maxtemp << w.totrain << endl;
}

鉴于您在下面提出的评论,您的代码在正确的轨道上 - 您已阅读整个文件,并拥有可用于操纵它的数据。你现在想要的是追踪年,雨和部分云。最简单的方法是创建另一个结构,并将其存储在向量中。结构将是这样的:

struct yeardata {
    string year; // could also be int, if you want to convert it to an ant
    int numberOfRain;
    int numberOfPartlyCloudy;
}

然后,当您遍历vw时(或者,当您阅读文件时。您仍然不需要vw向量),您将拥有一个yeardatas向量。检查向量以查看年份是否存在,以及是否未添加它,将两个int设置为0.然后,根据需要增加整数,并打印出该向量中的所有数据。

因为这是一项任务,所以我可以带你去。祝你好运!

相关问题