是否有可以逐行迭代文件的 C++ 迭代器?

2022-01-10 00:00:00 line file newline iterator c++

我想要一个 istream_iterator 风格的迭代器,它将文件的每一行作为字符串而不是每个单词返回.这可能吗?

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?

推荐答案

这个技巧已经被其他人发布了 在上一个线程中.

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

很容易拥有 std::istream_iterator 做你想做的事:

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

相关文章