Range-based loop over an input stream

前端 未结 4 1011
醉梦人生
醉梦人生 2021-02-08 16:57

To iterate over an input stream, we would usually use a std::istream_iterator like so:

typedef std::istream_iterator input_iterato         


        
4条回答
  •  忘了有多久
    2021-02-08 17:53

    Here is one possible solution. Sadly, it does require an extra structure:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    struct S {
      std::istream& is;
      typedef std::istream_iterator It;
      S(std::istream& is) : is(is) {}
      It begin() { return It(is); }
      It end() { return It(); }
    };
    
    int main () {
      std::ifstream file("myfile");
      for(auto& string : S(file)) {
        std::cout << string << "\n";
      }
    }
    

    Another solution is to derive from std::ifstream:

    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    struct ifstream : std::ifstream {
      // using std::ifstream::ifstream; I wish g++4.7 supported inheriting constructors!
      ifstream(const char* fn) : std::ifstream(fn) {}
      typedef std::istream_iterator It;
      It begin() { return It(*this); }
      It end() { return It(); }
    };
    
    int main () {
      ifstream file("myfile");
      for(auto& string : file) {
        std::cout << string << "\n";
      }
    }
    

提交回复
热议问题