Is there a C++ iterator that can iterate over a file line by line?

后端 未结 7 1020
忘了有多久
忘了有多久 2020-12-01 07:18

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?

7条回答
  •  一向
    一向 (楼主)
    2020-12-01 07:54

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

提交回复
热议问题