Link to home
Start Free TrialLog in
Avatar of prashant_n_mhatre
prashant_n_mhatre

asked on

Clearing stringstream

int main()
{
   string pnm;
   stringstream S;
   int x=123;
   int y=222;

   S << "xyz"  << x << "lpm" << y;
   
   pnm = S.str();
   cout << pnm << endl; // output should be xyz123lpm222

  // I would like to Clear 'S' - make it empty and reuse
  // to create another stream. (Modify its content)

   return 0;
}
Avatar of jkr
jkr
Flag of Germany image

I son't work a lot with stringstreams, but regarding the class hierarchy, calling 'S.flush()' should be enough...
Avatar of prashant_n_mhatre
prashant_n_mhatre

ASKER

doesn't work...
Thanks..I've figured out.

 S.seekp(0, ios::beg);

does that.
Are you going to delete the question?
Actually it will not work if I change the field length.
I need to add something like

freeze(false);

But that doesn't work with stringstream.
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Are you going to delete the question?
That was an accident.
EE is not working well right now!   I was tryign to post fo the longest time. Anyways to contineu--hopefully.

As I see you now realize, the problem with

   S.seekp(0, ios::beg);

is that it just moves the write position back to the start of the stream.  But the data already written stays there, so if you do.

   S <<"1234567890";
   S.seekp(0);
   S << "ABC";
   string AString = S.str();

This leaves AString with "ABC4567890" instead of just "ABC".

Now there is an expert who will tell you that the correct solution is to that the fix for this is

   S <<"1234567890";
   S.seekp(0);
   S << "ABC" << char(0);
   string AString = S.str();

But do not be fooled!  This just sticks a NUL terminator in the middle of the string data so that it appears like "ABC" is all that is stored.  its not.  it still stores the "567890" after that.  In fact the string's length() function will report this.   Don't fall for this!

Instead make use of the fact that you can store a new string data sequence in the stream object with the overlaoded str() member function.  i.e. you can do

   S.str("ABC");

and now the stream stores "ABC".  I you read from the stream you will read "ABC"  If you write to the stream you will wrote after the "ABC"  (unless you seek around.)  

In your case you want to set the stream to store an empty string, like

   S.str(string());

New the stream is empty.  It stores no data to read from the stream.  It stores no data that will be combined with data written to the stream.

Note that I am not sure how this operation effects the stram position.  You might still need to seek to the start of the stream after clearing its contents.
Okay, you shouldn't need to do a seekp(0) or seekg(0).  The str(string) member function will reset the read and write positions to 0.
Thanks all!!!