Try this:
int main()
{
std::fstream fin_fout("some.txt");
std::istream_iterator<std::string> beg(fin_fout),end;
std::distance(beg,end);//if this line is commented out it works fine but not if is uncommented
while (beg != end)
{
cout << *beg;
++beg;
}
return 0;
}
distance
on an input iterator will repeatedly call operator++
. However, this operation invalidates all copies of the iterator, because they all refer to the same underlying stream
This is logical: consider what the iterator represents: the current state of the input stream. As soon as you advance the iterator, that state changes. All other iterators representing the old state are therefore now referring to a state that no longer exists.
This is why you see this behaviour.
Getting a distance from two stream operators is moreover not a meaningful operation since streams don’t have a fixed length: streams represent transient state.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With