Stream iterators and exceptions

I played with istream iterators and exception handling a few days ago, and I came across this curiosity:

#include <iostream> #include <fstream> #include <iterator> #include <algorithm> using namespace std; int main(int argc, char* argv[]) { if (argc < 2) { cout << argv[0] << " <file>" << endl; return -1; } try { ifstream ifs(argv[1]); ifs.exceptions(ios::failbit | ios::badbit); istream_iterator<string> iss(ifs), iss_end; copy(iss, iss_end, ostream_iterator<string>(cout, "\n")); } catch (const ios_base::failure& e) { cerr << e.what() << endl; return -2; } return 0; } 

Why does a failure exception always occur after reading the last word of the input file?

+4
source share
3 answers

failbit set up whenever a read operation cannot extract any characters, whether because it fell into EOF or not.

 stringstream ss ("foo"); string s; int i; ss >> i; // sets failbit because there is no number in the stream ss.clear(); ss >> s; // sets eofbit because EOF is hit ss.clear(); ss >> s; // sets eofbit and failbit because EOF is hit and nothing is extracted. 
+3
source

Define the EOF condition by reading until an error occurs that throws an exception and then checks the cause of the failure.

To expand: istream_iterator becomes invalid when, after reading the value with →, the stream operator void * returns NULL. But for this, the → operator must set the fault bit, so raise an exception.

0
source
Good question. It would be nice to catch the other failures in this call, but continue normally when it gets into eof.

However, I have not used thread exceptions before. I think you could make a copy and check the status of the stream afterwards to detect other errors, for example:

 ifstream ifs(argv[1]); if (!ifs) { cerr << "Couldn't open " << argv[1] << '\n'; return -1; } //ifs.exceptions(ios::failbit | ios::badbit); istream_iterator<std::string> iss(ifs), iss_end; copy(iss, iss_end, ostream_iterator<std::string>(cout, "\n")); if (!ifs.eof()) { cerr << "Failed to read the entire file.\n"; return -2; } 
0
source

Source: https://habr.com/ru/post/1302868/


All Articles