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

read until a certain line from text in fstream

本文关键字:一行 fstream 文本 读取      更新时间:2023-10-16

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

当然有一种方法可以在不使用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向量),你会有一个年份数据的向量。 检查向量以查看年份是否存在,如果未添加年份,则将两个int设置为 0。 然后,根据需要递增整数,并打印出该向量中的所有数据。

既然是作业,那差不多是我能带你去的。 祝你好运!