I got an exception thrown when I try to read a file since I added characters in it. But I don't understand why. Content of the file :
12 58 c 10 -105.3 c 4 -30.5 f 3 -84.7 f
There is no whitespace after the final letter. The error occur after the while read all the line, he goes in again and crash.
Thanks in advance !
#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";
}