user2943407
user2943407

Reputation: 413

Reason for this output of stringstream?

I am trying to learn stringstream and I have the following code:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    stringstream os;
    os.str("Purohit");
    os << "Vipul" << endl;
    cout << os.str() << endl;
}

When I compile it and run it, I get the following output:

Vipul
t

Why? Shouldn't this output Purohit Vipul?

Upvotes: 3

Views: 113

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

This is because str method replaces the content of stringstresm, without placing the buffer pointer for the subsequent writes at the end of the stream. That is why when you output "Vipul\n" it writes over the "Purohit" string that you placed into the stream earlier:

Initial state

0 1 2 3 4 5 6
P u r o h i t
^

After the << write:

0 1 2 3 4 5  6
V i p u l \n t    

You could call seekg to set the position before appending the "Vipul" string, but an easier fix would be to use << for both writes.

Upvotes: 7

Related Questions