question

Krzysztofelechowski-3963 avatar image
0 Votes"
Krzysztofelechowski-3963 asked BarrnetZhou-MSFT edited

How to catch current stream position before istream_iterator

I am trying to create an extension of class istream_iterator that saves the input stream position before each read. How should I implement the constructor so that it can catch the stream position at the time the constructor was called? Because it is a subclass of istream_iterator, the constructor constructs the base class first; but after the base class has been constructed, the stream position will have changed (this is how istream_iterator works). Short of reimplementing istream_iterator (which is probably the best option because the istream_iterator does not let me ask its underlying stream for its current position, meaning that I need to keep another reference to the same input stream), what are my options here?

c++
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Viorel-1 avatar image
0 Votes"
Viorel-1 answered BarrnetZhou-MSFT edited

Check the next approach too:

 class MyIterator : istream_iterator<char>
 {
 public:
    
     MyIterator( istream& stream )
         : MyIterator( stream, stream.tellg() )
     {
     }
    
 private:
    
     MyIterator( istream& stream, istream::pos_type pos )
         : istream_iterator( stream ), startPos( pos )
     {
     }
    
     istream::pos_type const startPos;
 };
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thank you, I shall try that.

0 Votes 0 ·
BarrnetZhou-MSFT avatar image BarrnetZhou-MSFT Krzysztofelechowski-3963 ·

Is this problem solved? If it is solved, could you mark it as answer. This will be beneficial to other community. @Krzysztofelechowski-3963

0 Votes 0 ·
IgorTandetnik-1300 avatar image
0 Votes"
IgorTandetnik-1300 answered Krzysztofelechowski-3963 commented

Something like this should work:

 MyIterator::MyIterator(istream& stream)
     : istream_iterator((cur_pos = stream.tellg(), stream)) {}
· 10
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Something is nagging at the back of my mind. I recall some often-stated
advice that one should not derive from STL classes. Relates to the absence of
a virtual destructor as I recall. Or does this only apply to STL containers?

  • Wayne

0 Votes 0 ·
BarrySchwarz-8780 avatar image BarrySchwarz-8780 Krzysztofelechowski-3963 ·

It is a variable of the type returned by tellg. It will probably work with any integer type at least as large as int.

0 Votes 0 ·

Where is cur_pos declared?

0 Votes 0 ·
Show more comments