Modify contents of basic_ostream object in c++ or, deleting data contents of basic_ostream object

倖福魔咒の 提交于 2019-12-25 16:27:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!