Writing stringstream contents into ofstream

最后都变了- 提交于 2019-12-02 19:52:37

You can do this, which doesn't need to create the string. It makes the output stream read out the contents of the stream on the right side (usable with any streams).

outFile << ss.rdbuf();

If you are using std::ostringstream and wondering why nothing get written with ss.rdbuf() then use .str() function.

outFile << oStream.str();
2ndshot

When passing a stringstream rdbuf to a stream newlines are not translated. The input text can contain \n so find replace won't work. The old code wrote to an fstream and switching it to a stringstream losses the endl translation.

I'd rather write ss.str(); instead of ss.rdbuf(); (and use a stringstream).

If you use ss.rdbuf() the format-flags of outFile will be reset rendering your code non-reusable. I.e., the caller of GetHolesResults(..., std::ofstream &outFile) might want to write something like this to display the result in a table:

outFile << std::setw(12) << GetHolesResults ...

...and wonder why the width is ignored.

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