1

Possible Duplicate:
What is the purpose of ostringstream's string constructor?

I am facing below issue. I have an ostringstream say testStr. I first insert few characters inside it using <<

testStr << somechar;

Then I modified:

testStr.Str("some string")

so that now testStr is containing "Some String"

Now I want to add some characters(say " " and "TEST") at the end so that it can become "Some String TEST".

testStr << " " << "TEST";

But I am getting " TESTString". Please let me know what can be done?

Adding sample code:

#include <iostream>
#include <sstream>
int main() {
  std::ostringstream s;
  s << "Hello";
  s.str("WorldIsBeautiful");
  s << " " << "ENDS";
  std::cout << s.str() << std::endl;

}

Output is " ENDSIsBeautiful" where as I expected "WorldIsBeautiful ENDS".

Community
  • 1
  • 1
learningstack
  • 358
  • 1
  • 4
  • 15
  • 1
    Please just show the full code, from ostringstream instationation to the point where you retrieve the string from it; it seems like testStr is modified somewhere inbetween `testStr.Str("...")` and `testStr << ...`, and after the last statement you're showing. – codeling Sep 17 '12 at 06:45
  • I just tried it myself and I think I can reproduce the issue: http://codepad.org/tAgB1BEU - I didn't even know that ther is a `str` overload to *set* the string... – Frerich Raabe Sep 17 '12 at 06:50
  • that is indeed odd behavior, I didn't know ostringstream cleared the string on the first call to operator<< after calling `str(string)` - but so far I have only used `str(string)` to clear an `ostringstream`! No idea why it's implemented that way, it doesn't seem to be mentioned in the documentation I have read so far – codeling Sep 17 '12 at 06:57
  • @BoPersson, Good catch, I've not seen this behaviour yet, but I guess I was right minus the why. It's always a good time to learn. – chris Sep 17 '12 at 07:03

1 Answers1

2

I'm not overly sure, but it looks like it's still set to write at the beginning. To fix this, you can call s.seekp(0, std::ios_base::end); to set the output position indicator back to the end. I have a working sample here:

#include <iostream>
#include <sstream>

int main() {
  std::ostringstream s;
  s.str( "Hello" );
  s.seekp(0, std::ios_base::end);
  s << "x" << "World";
  std::cout << s.str() << std::endl;
}

Output:

HelloxWorld
chris
  • 60,560
  • 13
  • 143
  • 205
  • @learningstack, Be sure to read through Bo's link. It's pretty informative in explaining the why (which I had no idea about). – chris Sep 17 '12 at 07:04