3

I tried to initialize a std::ostringstream with a const std::string but the string returned by the str() method does not include the initial string. I compile with a company toolchain based on gcc-4.3.2 with C++11 enabled.

Example

#include <sstream>

const std::string str = "foo";
const std::string longStr = "barbarbar";

int main() {
  std::ostringstream ss1(str);
  std::ostringstream ss2{str};
  std::ostringstream ss3;
  ss3 << str;

  ss1 << longStr;
  ss2 << longStr;
  ss3 << longStr;

  std::cout << ss1.str() << std::endl;
  std::cout << ss2.str() << std::endl;
  std::cout << ss3.str() << std::endl;
}

Result

barbarbar
barbarbar
foobarbarbar

I expected all three lines to be equal, but only the ss3 solution provided the right result. I tried this code on code.sh and it did what was expected: concatenating str and longStr.

I found a similar situation here without much explanations on why it behaves that way: std::ostringstream overwriting initializing string

Why are the two first initializations not providing the expected result in my case? What can make std::ostringstream behave differently in different compilation contexts?

A. Gille
  • 912
  • 6
  • 23
  • The question in the dupe is not great, but the answer addresses your question. – cigien Sep 18 '20 at 17:21
  • Since the dupe doesn't provide a solution. You can redefine the `openstate` by adding it to the `ostringstream` constructor argument list `std::stringstream ss1(str, std::ios_base::app | std::ios_base::out);` this will allow you to append strings afterwards. also works with initializer list `{}`. – anastaciu Sep 18 '20 at 18:11
  • Then why does it works without specifying these options in the constructor call? – A. Gille Sep 21 '20 at 09:16

0 Answers0