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

后端 未结 7 1023
忘了有多久
忘了有多久 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:56

    In a related thread iterate-over-cin-line-by-line quoted above, Jerry Coffin described "another possibility (which) uses a part of the standard library most people barely even know exists." The following applies that method (which was what I was looking for) to solve the iterate-over-file-line-by-line problem as requested in the current thread.

    First a snippet copied directly from Jerry's answer in the related thread:

    struct line_reader: std::ctype {
    line_reader(): std::ctype(get_table()) {}
    static std::ctype_base::mask const* get_table() {
        static std::vector rc(table_size, std::ctype_base::mask());
        rc['\n'] = std::ctype_base::space;
        return &rc[0];
    }}; 
    

    And now, imbue the ifstream with the custom locale as described by Jerry, and copy from infstream to ofstream.

    ifstream is {"fox.txt"};
    is.imbue(locale(locale(), new line_reader()));
    istream_iterator ii {is};
    istream_iterator eos {};
    
    ofstream os {"out.txt"};
    ostream_iterator oi {os,"\n"};
    
    vector lines {ii,eos};
    copy(lines.begin(), lines.end(), oi);
    

    The output file ("out.txt") will be exactly the same as the input file ("fox.txt").

提交回复
热议问题