Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected iterator behavior as a member variable

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading