Rewrting over an ostringstream object with seekp(0)

  • Thread starter Thread starter Maitre Bart
  • Start date Start date
M

Maitre Bart

The following simple program overwrites the content of an ostriungstream
object.

#include <iostream>
#include <sstream>

using namespace std;

int main()
{
ostringstream oss;

oss << "0123456789" << ends;
cout << '[' << oss.str() << ']' << endl;

oss.seekp(0);
oss << "toto" << ends;
cout << '[' << oss.str() << ']' << endl;

return 0;
}

In MS-DEV-6, the output was (as I suspected):

[0123456789]
[toto]

In MS-DEV-7.1, the output is (note the extra space):

[0123456789 ]
[toto 56789 ]

May someone tell me what is wrong?
 
You get the extra space because you appended 0 characters. ends is
deprecated now, it's coming from a decade old C++ library, when a string
stream didn't use std::string but a char*. What "<< ends" does it puts a
0 byte to the end of the string, and that looks like a space. For more info:
http://tinyurl.com/69g64

The other problem is that seekp doesn't clear the buffer, it only sets
the write (put) pointer to the beginning. You are partially overwriting
the previous contents.

Your code should be (untested):

ostringstream oss;

oss << "0123456789";
cout << '[' << oss.str() << "]\n";

oss.str(""); // this should clear the stream
oss << "toto";
cout << '[' << oss.str() << "]\n";

BTW, endl has a totally different meaning than "\n". endl also flushes
the buffer, which has performance issues. I wouldn't use endl unless I
explicitly wanted to flush the buffer. It's old habit too, but it's not
necessarily a mistake.

VC++ 6 is wrong, VC++ 7.1 is right in this case. Hope this helps.

Tom
 
Back
Top