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;
}
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_iteratorto 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).