Why is stripstringstream NULL?

I have a line whose last part (suffix) needs to be changed several times, and I need to generate new lines. I am trying to use ostringstream to do this, as I think using streams will be faster than string concatenation. But when the previous suffix is ​​larger than the previous one, it becomes corrupted. The stream also disables null characters.

#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 to Hello World. How should I do it? Is there any other way to do this faster?

Edit: Adds std::ends. But I wonder how it works domestically. I would also like to know if there are faster ways to do the same.

+5
3

. ++ NUL, , , , . ostream::write ostream::put, - , char* ( ), , .

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

"World" . C . "\0" \0. operator<<(ostream&, const char*) \0. , os << "World\0!". ! , operator<< \0.

, ostringstream. C aka const char*.

+9

Why do you think stream operation is faster than string? And why build a line before exiting in cout?

If you need a prefix for your output, you can just do it like this

const std::string prefix = "Hello ";

std::cout << prefix << "Universe" << std::endl;
std::cout << prefix << "World" << std::endl;
0
source

All Articles