Search code examples
c++string-concatenationostringstream

Why does ostringstream strip NULL?


I have a string whose last part(suffix) needs to be changed several times and I need to generate new strings. I am trying to use ostringstream to do this as I think, using streams will be faster than string concatenations. But when the previous suffix is greater than the later one, it gets messed up. The stream strips off null characters too.

#include<iostream>
#include<sstream>

using namespace std;

int main()
{
  ostringstream os;
  streampos pos;
  os << "Hello ";
  pos = os.tellp();
  os << "Universe";
  os.seekp(pos);
  cout<<  os.str() << endl;
  os << "World\0";
  cout<<  os.str().c_str() << endl;
  return 0;
}

Output

Hello Universe
Hello Worldrse

But I want Hello World. How do I do this? Is there anyother way to do this in a faster manner?

Edit: Appending std::ends works. But wondering how it works internally. Also like to know if there are faster ways to do the same.


Solution

  • It doesn't strip anything. All string literals in C++ are terminated by NUL, so by inserting one manually you just finish the string, as far as anyone processing it is concerned. Use ostream::write or ostream::put, if you need to do that — anything that expects char* (with no additional argument for size) will most likely treat it specially.

    os.write("World\0", 6);