To iterate over an input stream, we would usually use a std::istream_iterator
like so:
typedef std::istream_iterator input_iterato
Here is one possible solution. Sadly, it does require an extra structure:
#include
#include
#include
#include
#include
struct S {
std::istream& is;
typedef std::istream_iterator It;
S(std::istream& is) : is(is) {}
It begin() { return It(is); }
It end() { return It(); }
};
int main () {
std::ifstream file("myfile");
for(auto& string : S(file)) {
std::cout << string << "\n";
}
}
Another solution is to derive from std::ifstream
:
#include
#include
#include
#include
#include
struct ifstream : std::ifstream {
// using std::ifstream::ifstream; I wish g++4.7 supported inheriting constructors!
ifstream(const char* fn) : std::ifstream(fn) {}
typedef std::istream_iterator It;
It begin() { return It(*this); }
It end() { return It(); }
};
int main () {
ifstream file("myfile");
for(auto& string : file) {
std::cout << string << "\n";
}
}