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

后端 未结 7 993
忘了有多久
忘了有多久 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 08:00

    EDIT: This same trick was already posted by someone else in a previous thread.

    It is easy to have std::istream_iterator do what you want:

    namespace detail 
    {
        class Line : std::string 
        { 
            friend std::istream & operator>>(std::istream & is, Line & line)
            {   
                return std::getline(is, line);
            }
        };
    }
    
    template<class OutIt>
    void read_lines(std::istream& is, OutIt dest)
    {
        typedef std::istream_iterator<detail::Line> InIt;
        std::copy(InIt(is), InIt(), dest);
    }
    
    int main()
    {
        std::vector<std::string> v;
        read_lines(std::cin, std::back_inserter(v));
    
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题