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

thehouse picture thehouse · Feb 18, 2010 · Viewed 45.2k times · Source

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?

Answer

Manuel picture Manuel · Feb 18, 2010

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