问题
I get a ostream
object reference in a function. It contains a string which I need to modify.
I copied the contents of the ostream
using rdbuf()
function into a stringstream
.
Now I need to copy the updated stringstream (the underlying string that is) back to the ostream object. How can I do this?
I searched ways of erasing the contents of the ostream, but could not find one.
Note: I cannot change the implementation of other functions, i.e., I an unable to use ostringstream
(which I know can solve my problem).
回答1:
You can try to change the current position in the stream using ostream::seekp()
or streambuf::pubseekpos()
:
std::ofstream out;
out.seekp(-10, std::ios_base::cur); // move back 10 positions from current location
out.rdbuf()->pubseekpos(12); // move to position 12
Keep in mind that:
- this might fail if the underlying destination of the data does not support seeking (e.g. the streambuf might actually write the data to a socket let's say)
- if it works for your particular type of stream, you have to keep count of positions and lengths and how much you overwrite (if the new value has a different length then the old value that you want to replace in the stream).
来源:https://stackoverflow.com/questions/31132025/modify-contents-of-basic-ostream-object-in-c-or-deleting-data-contents-of-bas