I have a class that has two member variables and a file that in each line has to numbers. I have implemented std::istream& operator>>
for that class. I would like to read this file and for each line in it create an object of my class. I do not want to manually check stream status each time I read from it, but rather I want it to throw an exception and then handle it.
My problem is, that when my code reads all the lines, but then it tries to read one more, and throws an std::fstream::failure
exception. How can I avoid this, but have it be thrown when something bad actually happens (IO error)?
#include <exception>
#include <fstream>
#include <iostream>
#include <vector>
class A {
public:
A() : m_x{0}, m_y{0} {}
A(int x, int y) : m_x{x}, m_y{y} {}
private:
int m_x, m_y;
};
std::istream& operator>>(std::istream& is, A& a) {
int x, y;
is >> x >> y;
a = A{x, y};
return is;
}
void load(std::vector<A>& v) {
std::ifstream file;
file.exceptions(std::fstream::failbit | std::fstream::badbit);
try {
file.open("file");
// This does not work! What should I do?
A a;
while(file >> a) {
v.push_back(a);
}
} catch (const std::fstream::failure&) {
file.close();
throw;
}
}
int main() {
std::vector<A> v;
try {
load(v);
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}