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

后端 未结 7 1025
忘了有多久
忘了有多久 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:37

    The standard library does not provide iterators to do this (although you can implement something like that on your own), but you can simply use the getline function (not the istream method) to read a whole line from an input stream to a C++ string.

    Example:

    #include 
    #include 
    #include 
    #include 
    
    using namespace std;
    
    int main()
    {
        ifstream is("test.txt");
        string str;
        while(getline(is, str))
        {
            cout<

提交回复
热议问题