开发者

How do you setup istream_iterator to not ignore blank lines

开发者 https://www.devze.com 2023-01-10 04:18 出处:网络
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 \"\".

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 开发者_JS百科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_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).


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消