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

后端 未结 7 1007
忘了有多久
忘了有多久 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 07:57

    Here is a solution. The exemple print the input file with @@ at the end of each line.

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    class line : public string {};
    
    std::istream &operator>>(std::istream &is, line &l)
    {
        std::getline(is, l);
        return is;
    }
    
    int main()
    {
        std::ifstream inputFile("input.txt");
    
        istream_iterator begin(inputFile);
        istream_iterator end;
    
        for(istream_iterator it = begin; it != end; ++it)
        {
            cout << *it << "@@\n";
        }
    
        getchar();
    }
    

    Edit : Manuel has been faster.

提交回复
热议问题