I know that stringstream
can be updated with stringstream::str()
, but if I input something else into the stringstream
after that, it is not working as expected. The following snippet demonstrates the phenomenon:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
stringstream ss; //ostringstream gives the same output
ss << "Original string ";
ss.str("Updated string ");
ss << "sth else";
cout << ss.str() << endl;
}
I expect to get the output
Updated string sth else
But it actually outputs
sth elsestring
It seems that rather that appending the newly inputted string at the end of the current string (in my case Updated string
), it tries to override it from the beginning. What is wrong with my code?
Here's a live demo
You need to add std::ios_base::app
to the openmode
. It ensures that the stringstream
object seeks to the end of the stream before every write. Try this:
stringstream ss(std::ios_base::app|std::ios_base::in|std::ios_base::out);
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