当我尝试读取一个文件时,因为我在其中添加了字符,所以引发了一个异常。 但我不明白为什么。 文件内容:
12 58 c 10-105.3 c 4-30.5 f 3-84.7 f
最后一个字母后面没有空格。 错误发生在while读取所有行之后,他再次进入并崩溃。
提前谢谢!
#include <iostream>;
#include<fstream>
#include<string>
#include<vector>
#include<random>
using namespace std;
struct Reading {
int hour;
double temp;
char t;
};
istream& operator>>(istream& is, Reading r)
{
return is >> r.hour >> r.temp >> r.t;
}
vector<Reading> read_file()
{
string filename{ "raw_temp.txt" };
ifstream ifs{ filename };
ifs.exceptions(ifs.exceptions() | ios_base::failbit);
//if (!ifs) error("can't open input file ", filename);
vector<Reading> r;
while (!ifs.eof())
{
Reading e{};
ifs >> e;
if (e.t == 'c') e.temp = e.temp * 9 / 5 + 32;
r.push_back(e);
}
return r;
}
int main()
try {
vector<Reading> r;
r = read_file();
}
catch (exception & e)
{
cerr << e.what();
}
catch (...)
{
cerr << "Unknown exception";
}
这样编写代码
vector<Reading> r;
Reading e;
while (ifs >> e)
{
...
}
然后阅读此答案,解释while(!ifs.eof())
错误的原因