Home > Back-end >  Unexpected iterator behavior as a member variable
Unexpected iterator behavior as a member variable

Time:04-22

I'm having trouble with iterators:

class Foo {
 private:
  std::istream_iterator<char> it_;

 public:
  Foo(std::string filepath) {
    std::ifstream file(filepath);
    it_ = std::istream_iterator<char>(file);
  }

  char Next() {
    char c = *it_;
    it_  ;
    return c;
  }

  bool HasNext() { return it_ != std::istream_iterator<char>(); }
};

int main() {
  Foo foo("../input.txt");

  while (foo.HasNext()) {
    std::cout << foo.Next();
  }

  std::cout << std::endl;

  return EXIT_SUCCESS;
}

The file input.txt is just Hello, world!.

But when I run this, it only prints H. It seems to have something to do with storing the iterator as a member variable?

CodePudding user response:

Here:

Foo(std::string filepath) {
    std::ifstream file(filepath);
    it_ = std::istream_iterator<char>(file);
}

You store an iterator to file. Once this constructor returns files destructor is called and all iterators to the ifstream become invalid. It is similar to using a pointer to a no longer existing object. You need a ifstream to read from, the iterator just refers to contents that can be extracted from the file, but if the file is gone you cannot extract from it. Store the ifstream as member too.

You can read the first character, because already on construction of the std::istream_iterator the first character is extracted from the file.

  • Related