【发布时间】:2015-11-11 18:31:56
【问题描述】:
我必须编写一个程序来读取具有两列的 .dat 文件。我只对一个感兴趣。它有多组 120 个元素,所以我想将文件分成 120 个元素的组并计算每组的平均值。代码是这样的:
#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
using namespace std;
int i, k=0;
double temp [120];
double tmean, total=0;
int main()
{
ifstream fin ("P01-05 tensione di vapore di riferimento fino 180°C.dat");
if (!fin)
{
cerr << "\nErrore: non si puo aprire il file.\n" << endl;
exit(1);
}
string line;
ofstream fout;
fout.open("tmean.dat", ios::out);
fout << "Tmean" << endl;
while (fin >> std::skipws && !fin.eof())
{
for(i=0; i<120; i++)
{
getline(fin,line);
istringstream ss(line);
double col1;
double col2;
ss >> col1; //col1=TIME
ss >> col2; //col2=TEMPERATURE
temp[i] = col2;
total += temp[i];
k++;
}
tmean = total/k;
fout << tmean << endl;
}
return 0;
}
我已经编译并执行了它,但它不起作用,它就像一个无限循环。它没有给我任何输出。为什么?
【问题讨论】:
-
执行后tmean.dat文件有内容吗?有Tmean线吗?
-
@SashaPachev 不,它不会打开文件 tmean.dat,因为我认为程序会导致无限循环!
-
您是否尝试过使用调试器?添加了打印语句以显示中间步骤?这些都是您在此处发布之前应该执行的所有基本调试步骤。
-
首先,删除输入文件名中的空格。其次,使用调试器逐步运行您的代码。 那么你应该问问周围,如果你仍然卡住。另请查看创建minimal, complete, and verifiable example。您的数据文件丢失。
-
您的代码中没有任何无限循环,您一定是误解了您所看到的内容