When trying to concatenate a string in ostringstream, which string contents are modified and reconstructed, string get added at beginning [duplicate]

StackOverflow https://stackoverflow.com/questions/12454255

  •  02-07-2021
  •  | 
  •  

Frage

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".

War es hilfreich?

Lösung

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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top