Pregunta

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?

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top