我怎么能从一个有很多行的.dat文件中读取,并在数组中只收集几个值,直到EOF
How can i read from a file .dat with a lot of lines and gather just few values in arrays until EOF?
我必须制作一个从文件.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开始;德里克已经对另一个问题发表了评论。
相关文章:
- 如何在C++中比较两个char数组
- 使用嵌套函数数组是个好主意吗?
- 链表数组(5 个队列)
- 是否有可能通过溢出 C 中的第一个元素来写入数组第二个元素
- 如何从数组中仅返回几个值
- 我有一个包含几个重复元素的数组,我想找到最接近数组末尾的重复元素的索引
- 使用C - CIN获取几个整数数字,然后将它们放入数组中
- 关于C++中数组的几个问题
- 如何创建一个一维数组来容纳几个二维数组
- 我正在尝试设置几个不同的多维数组,但无法弄清楚为什么这不起作用
- 指向数组第一个元素的指针的地址
- 用 std::valarray 替换 POD C 样式数组是个坏主意吗?
- 如何截断前几个字符字符数组 C++
- OpenGL:两个顶点数组 + 两个索引数组
- c++多维数组多个数据类型
- 使用C++AMP处理大型数组(65536+个元素)
- 在几个顺序数组元素中输入相同的值
- 我怎么能从一个有很多行的.dat文件中读取,并在数组中只收集几个值,直到EOF
- 我的字符数组只显示最后几个字符.c++
- 在c++中使用MKL函数初始化数组是个好主意吗?