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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With