Best way to empty stringstream?

41,140

I've always done:

s.clear();//clear any bits set
s.str(std::string());

@litb gets into more detail about how to seekp to the start of the stream combined with std::ends you can keep your allocated size.

Share:
41,140
Admin
Author by

Admin

Updated on May 08, 2020

Comments

  • Admin
    Admin almost 4 years

    One of the possibilities is:

    somestringstream.str("");
    

    But is it most optimal? Is there any way to preserve stringstream internal buffer, so that following operator<<() calls would not require to reserve memory again?

  • Milan
    Milan almost 15 years
    or simply ss.str(""); //more intuitive
  • Drew Dormann
    Drew Dormann almost 15 years
    @milan1612: You would still need to clear the bits, and sending a C-style char* will be slower.
  • Andreas Spindler
    Andreas Spindler over 12 years
    ..and this explains why the s.str(std::string()) variant could be more efficient.