Range-based loop over an input stream

前端 未结 4 1290
生来不讨喜
生来不讨喜 2021-02-08 17:06

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:40

    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";
      }
    }
    

提交回复
热议问题