Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ stringstream not working correctly after updated with stringstream::str()

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

like image 638
Jing Li Avatar asked Feb 10 '15 23:02

Jing Li


1 Answers

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);
like image 101
Pradhan Avatar answered Oct 15 '22 06:10

Pradhan