The task is to read numbers from file to vector. Format is: one number per line. I want to make with STL-style. So, I wrote such code:
::std::deque<size_t> Input(const ::std::string& filename) {
::std::deque<size_t> result;
try {
::std::ifstream file(filename.c_str(), ::std::ios::binary);
file.exceptions(::std::ifstream::failbit |
::std::ifstream::badbit);
::std::copy(::std::istreambuf_iterator<size_t>(file),
::std::istreambuf_iterator<size_t>(),
::std::back_inserter(result));
} catch ( ::std::exception& e ) {
::std::cout << e.what() << ::std::endl;
}
return result;
}
It works fine, and I get what I want (all numbers from the file), but also I get an exception with failbit at end of file. What’s the problem? I don’t want to use getline() and parse by hand — wanna ask STL do it for me.
UPDATE: I checked — there is no new line at the end of file.
TL;DR: If the stream run out of content while trying to read a new value,
failbitis set.It’s defined in the standard that using a
istream_iteratorhas the same effect as doing:Which in the case with handling integers (such as
size_t) will results in calls to the below (can be read about under 27.6.1.2.2/2 – lib.istream.formatted.arithmetic).erris passed by reference and will be set to whatever errors the function might run into. Below is a snippet from the standards definition ofuse_facet<numget> (loc).get:TL;DR: If the stream run out of content while trying to read a new value,
failbitis set.