Pratap Biswakarma
Pratap Biswakarma

Reputation: 117

If I extract something from a stream, does the stream not contain what I extracted anymore?

If I have code like below and I store "This" in str first from stream streem:

using namespace std;
int main()
{
    istringstream streem("This is the content in the stream.");
    string str;
    streem>>str;
    cout<<str; //This will cout "This"

If I do streem>>str again and cout<<str again, this will display is. So does this mean that "This" does not exist in the istringstream anymore? What aboutfile streams`, because they retain data?

Upvotes: 0

Views: 80

Answers (1)

M.M
M.M

Reputation: 141628

The answer is different for different streams .

The stringstream has a memory buffer and an indicator that remembers where you were up to on the reading. So the next read starts where the previous read left off.

File streams work in a similar way, they remember which point of the file they are up to. In both cases you can change position (including resetting to the beginning) using seekg.

File streams don't have separate read and write positions, so this same code might behave differently for a file stream . (In fact I think it causes undefined behaviour to read and write without an intervening seek).

Other input streams might not have seekable buffers, e.g. cin .

Upvotes: 2

Related Questions