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?
Here is a pretty clean approach that uses boost::tokenizer. This returns an object providing begin() and end() member functions; for a complete interface, see the documentation of the tokenizer class.
#include
#include
#include
using istream_tokenizer = boost::tokenizer,
std::istreambuf_iterator>;
istream_tokenizer line_range(std::istream& is);
{
using separator = boost::char_separator;
return istream_tokenizer{std::istreambuf_iterator{is},
std::istreambuf_iterator{},
separator{"\n", "", boost::keep_empty_tokens}};
}
This hardcodes char as the stream's character type, but this could be templatized.
The function can be used as follows:
#include
std::istringstream is{"A\nBB\n\nCCC"};
auto lines = line_range(is);
std::vector line_vec{lines.begin(), lines.end()};
assert(line_vec == (std::vector{{"A", "BB", "", "CCC"}}));
Naturally, it can also be used with an std::ifstream created by opening a file:
std::ifstream ifs{"filename.txt"};
auto lines = line_range(ifs);