tonicebrian
tonicebrian

Reputation: 4795

How do you setup istream_iterator to not ignore blank lines

I'm having problems with istream_iterator reading a file because it ignores blank lines, but I need that those blank lines are included as "".

How should I modify the program below to get the 5 lines in my vector?

#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <iterator>

using namespace std;
int main(int argc, const char *argv[])
{
    string  test = "There\nare\n\nfive\nstrings";
    stringstream stream(test);
    vector<string> v;
    copy(istream_iterator<string>(stream),istream_iterator<string>(),back_inserter(v));
    cout << v.size() << endl;
    return 0;
}

Upvotes: 1

Views: 2204

Answers (2)

Cubbi
Cubbi

Reputation: 47438

If newlines are the only delimiters in your string, you can set up boost.tokenizer to keep empty tokens, and parse with it:

#include <iostream>
#include <string>
#include <vector>
#include <boost/tokenizer.hpp>
int main()
{
        std::string  test = "There\nare\n\nfive\nstrings";

        boost::char_separator<char> sep("\n", "", boost::keep_empty_tokens);
        boost::tokenizer<boost::char_separator<char> > tokens(test, sep);

        std::vector<std::string> v(tokens.begin(), tokens.end());
        std::cout << v.size() << std::endl;
}

Otherwise, yes, line input iterators and line proxies are great general case solutions.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490158

The problem here isn't really with istream_iterator - it's with streams, which are set up to treat all runs of consecutive "white space" as a single delimiter.

As I outlined in a previous answer, there are a number of ways to get istream_iterator to read line-by-line though. Note that these will work a bit differently under one other circumstance: if you have more than one word on a line, like: "There are\nfour\n\nstrings", this would read "There are" as a single string, where your original would read it as two separate strings. I'm not sure what you really want in that case though (or maybe it'll never arise, so you don't care).

Upvotes: 1

Related Questions