You are here

How to clear an ostringstream?

Set the seek position of the stream (the position where something will be inserted into the stream) to the beginning. But consider that you must terminate writing to the stream with a std:ends. Otherwise you get the spare part of the former use of the string stream to your output string.
Example:
  std::ostringstream ost;
  std::string sstr;

  ost << "Some output abcdefgh";
  sstr = ost.str();
  // state: sstr = "Some output abcdefgh"

  ost.seekp(0);
  ost << "Short output ";
  sstr = ost.str();
  // state: sstr = "Short output bcdefgh"

  // Next attempt
  ost.seekp(0);
  ost << "Short output " << std::ends;
  sstr = ost.str();
  // Zustand : sstr = "Short output "