我怎么能从一个有很多行的.dat文件中读取,并在数组中只收集几个值,直到EOF

How can i read from a file .dat with a lot of lines and gather just few values in arrays until EOF?

本文关键字:数组 几个 EOF 直到 文件 一个 怎么能 dat 读取      更新时间:2023-10-16

我必须制作一个从文件.dat中读取的程序,该文件有两列,但我只对其中一列感兴趣。每个列都包含很多值,每个值都存储在一行中。我想把它们收集成120个元素的组(数组),然后计算平均值,这样进行直到EOF。计算完可用性后,我将其保存在一个外部文件中。我写的代码是这样的:

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<cmath>
using namespace std;
int i, k=1;
double temp [120];
double tmean, total=0;
int main()
{
ifstream fin ("Data_Acquisition(1).dat");
if (!fin)
{
    cerr << "nError: the file can't be open.n" << endl;
    exit(1);
}
string line;
ofstream fout;
fout.open("tmean.dat", ios::out);
fout << "Tmean" << endl;
for(i=0; i<=120; i++)
{
    getline(fin,line);
    istringstream ss(line);    
    double col1;      
    double col2;      
    ss >> col1;  
    ss >> col2;
    temp[i] = col2;
    total += temp[i];
    k++;
}
tmean = total/k;
fout << tmean << endl;
}

我的问题是:一旦计算出第一组值的可用性,我怎么能对程序说继续使用其他值,直到文件结束?

您当前有一个内部循环。。。

...
for(i=0; i<=120; i++)
{
    ...
}
tmean = total/k;
fout << tmean << endl;

把它包在外for环里。。。

while (fin >> std::skipws && !fin.eof())
{
    for(i=0; i<=120; i++)
    {
        ...
    }
    tmean = total/k;
    fout << tmean << endl;
}

您可能也想修复这些错误:k从1开始,每次读取值都会递增,因此最终会比应该的值多1:从0开始;德里克已经对另一个问题发表了评论。