How do I iterate over cin line by line in C++?

后端 未结 4 740
别跟我提以往
别跟我提以往 2020-11-22 09:53

I want to iterate over std::cin, line by line, addressing each line as a std::string. Which is better:

string line;
while (getline         


        
4条回答
  •  隐瞒了意图╮
    2020-11-22 10:34

    What I have (written as an exercise, but perhaps turns out useful one day), is LineInputIterator:

    #ifndef UB_LINEINPUT_ITERATOR_H
    #define UB_LINEINPUT_ITERATOR_H
    
    #include 
    #include 
    #include 
    #include 
    
    namespace ub {
    
    template 
    class LineInputIterator :
        public std::iterator
    {
    public:
        typedef typename StringT::value_type char_type;
        typedef typename StringT::traits_type traits_type;
        typedef std::basic_istream istream_type;
    
        LineInputIterator(): is(0) {}
        LineInputIterator(istream_type& is): is(&is) {}
        const StringT& operator*() const { return value; }
        const StringT* operator->() const { return &value; }
        LineInputIterator& operator++()
        {
            assert(is != NULL);
            if (is && !getline(*is, value)) {
                is = NULL;
            }
            return *this;
        }
        LineInputIterator operator++(int)
        {
            LineInputIterator prev(*this);
            ++*this;
            return prev;
        }
        bool operator!=(const LineInputIterator& other) const
        {
            return is != other.is;
        }
        bool operator==(const LineInputIterator& other) const
        {
            return !(*this != other);
        }
    private:
        istream_type* is;
        StringT value;
    };
    
    } // end ub
    #endif
    

    So your loop could be replaced with an algorithm (another recommended practice in C++):

    for_each(LineInputIterator<>(cin), LineInputIterator<>(), do_stuff);
    

    Perhaps a common task is to store every line in a container:

    vector lines((LineInputIterator<>(stream)), LineInputIterator<>());
    

提交回复
热议问题