为什么这段代码没有给出任何输出?这似乎是一个无限循环
Why this code doesn't give any output? It seems like an infinite loop
我必须制作一个程序,从一个有两列的.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)
是包装宏的标准方法,因此它可以在if else
语句中正常工作:如果您很好奇,可以搜索有关它的详细信息。
#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 << "Tmeann";
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.");
}
相关文章:
- 当调用switch语句中的函数时(即使函数不包含循环),似乎是永不结束的循环的问题
- 为什么文件不是由 F 流创建的,或者即使它是输出只是垃圾值?
- 工会成员的析构函数似乎是自动调用的
- 对GLFW / Vulkan的未定义引用,尽管库似乎是链接的
- 使用几何着色器的图层渲染似乎只输出图像数组的第一层
- C 程序如果功能中的语句不执行.在逻辑上似乎是错误的
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- C++随机函数给出的相同整数是输出的两倍
- 为什么没有参数的构造函数似乎是此代码的问题
- 类中的重载函数(Students())是输出输入的信息,但它不起作用
- 立方体的正态似乎是向内指向
- 对于特定情况的整数溢出似乎是由整数溢出引起的错误
- 在Stdout上似乎是僵局
- 这个逻辑似乎是正确的,但它不起作用.有没有错
- Ofstream似乎没有输出
- 有没有更好的方法可以使此代码线程安全?线程局部静态似乎是一个生硬的工具
- C 设置了双重的精度(不是输出)
- Travis CI似乎是从错误的Stdlib读书
- 我的功能似乎是正确的,但我会收到编译错误
- 为什么这段代码没有给出任何输出?这似乎是一个无限循环