I would like to get an istream_iterator-style iterator that returns each line of the file as a string rather than each word. Is this possible?
In a related thread iterate-over-cin-line-by-line quoted above, Jerry Coffin described "another possibility (which) uses a part of the standard library most people barely even know exists." The following applies that method (which was what I was looking for) to solve the iterate-over-file-line-by-line problem as requested in the current thread.
First a snippet copied directly from Jerry's answer in the related thread:
struct line_reader: std::ctype {
line_reader(): std::ctype(get_table()) {}
static std::ctype_base::mask const* get_table() {
static std::vector rc(table_size, std::ctype_base::mask());
rc['\n'] = std::ctype_base::space;
return &rc[0];
}};
And now, imbue the ifstream with the custom locale as described by Jerry, and copy from infstream to ofstream.
ifstream is {"fox.txt"};
is.imbue(locale(locale(), new line_reader()));
istream_iterator ii {is};
istream_iterator eos {};
ofstream os {"out.txt"};
ostream_iterator oi {os,"\n"};
vector lines {ii,eos};
copy(lines.begin(), lines.end(), oi);
The output file ("out.txt") will be exactly the same as the input file ("fox.txt").