我必须编写一个程序来读取具有两列的 .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;
}
我已经编译并执行了它,但它不起作用,它就像一个无限循环。它没有给我任何输出。为什么?
最佳答案
鉴于您是初学者,这里有一些代码展示了如何检查您的输入操作是否成功,否则会输出一些有用的错误消息以帮助您找到文件中的违规行。
注意事项:
错误消息中的“[i]”值是当前正在读取的“组”中的相对行号,而不是从文件开头算起的绝对行号。
空行仅在组之间被接受(
std::skipws
将跳过它)。FATAL
宏的使用可能令人困惑:总而言之,只有宏可以接受像"i " << i
这样的参数。并将它们添加到流操作中。do {
...} while (false)
thing 是包装宏的标准方法,因此它可以在if else
中正常工作statements:有兴趣的可以自行搜索。
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#define FATAL(MSG) \
do { \
std::cerr << "Errore: " << MSG << '\n'; \
exit(1); \
} while (false)
int main()
{
if (std::ifstream fin{"P01-05 tensione di vapore di riferimento fino 180°C.dat"})
{
if (std::ofstream fout{"tmean.dat"})
{
fout << "Tmean\n";
while (fin >> std::skipws && !fin.eof())
{
const int group_size = 120;
double temp[group_size];
double total = 0;
for (int i=0; i < group_size; ++i)
{
std::string line;
if (getline(fin, line))
{
std::istringstream ss(line);
double time;
if (ss >> time >> temp[i])
total += temp[i];
else
FATAL("unable to parse 2 doubles from line '"
<< line << "' for [" << i << ']');
}
else
// will rarely happen after checking !eof()
FATAL("failed to read needed line from file for ["
<< i << ']');
}
double tmean = total / group_size;
fout << tmean << '\n';
}
}
else
FATAL("could not open output file.");
}
else
FATAL("non si puo aprire il file.");
}
关于c++ - 为什么这段代码没有给出任何输出?这似乎是一个无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33657426/