Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
balki Avatar asked Jul 14 '11 07:07

balki


1 Answers

The string "World" is already null-terminated. That's how C strings work. "World\0" has two \0 characters. Therefore, operator<<(ostream&, const char*) will treat them the same, and copy all characters up to \0. You can see this even more clearly, if you try os << "World\0!". The ! will not be copied at all, since operator<< stopped at the first \0.

So, it's not ostringstream. It's how C strings aka const char* work.

like image 110
MSalters Avatar answered Sep 19 '22 21:09

MSalters