Take the 2-minute tour ×

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;
    string  test = "There\nare\n\nfive\nstrings";
    stringstream stream(test);
    vector<string> v;
    cout << v.size() << endl;
    return 0;
share|improve this question
For reading lines with istream_iterator, the solution I like most is the line proxy class from this answer: stackoverflow.com/questions/1567082/… –  UncleBens Aug 5 '10 at 15:37
@UncleBens: Beating me to putting up a link to my own previous answer! That's just not fair! :-) –  Jerry Coffin Aug 5 '10 at 15:40
add comment

2 Answers

up vote 1 down vote accepted

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).

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer


