c++istream-iterator

getline vs istream_iterator


Should there be a reason to preffer either getline or istream_iterator if you are doing line by line input from a file(reading the line into a string, for tokenization).


Solution

  • I sometimes (depending on the situation) write a line class so I can use istream_iterator:

    #include <string>
    #include <vector>
    #include <iterator>
    #include <iostream>
    #include <algorithm>
    
    struct Line
    {
        std::string lineData;
    
        operator std::string() const
        {
            return lineData;
        }
    };
    std::istream& operator>>(std::istream& str,Line& data)
    {
        std::getline(str,data.lineData);
        return str;
    }
    
    int main()
    {
         std::vector<std::string>    lines(std::istream_iterator<Line>(std::cin),
                                           std::istream_iterator<Line>());
    }