我必须制作一个程序来读取文件 .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 开始;并且 Derek 已经对另一个问题发表了评论。
关于c++ - 我如何从包含很多行的文件 .dat 中读取并在 EOF 之前只收集数组中的几个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33655429/