Writing stringstream contents into ofstream

前端 未结 4 833
情歌与酒
情歌与酒 2021-02-01 00:46

I\'m currently using std::ofstream as follows:

std::ofstream outFile;
outFile.open(output_file);

Then I attempt to pass a st

相关标签:
4条回答
  • 2021-02-01 01:18

    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.

    0 讨论(0)
  • 2021-02-01 01:32

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

    outFile << oStream.str();
    
    0 讨论(0)
  • 2021-02-01 01:33

    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();
    
    0 讨论(0)
  • 2021-02-01 01:36

    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.

    0 讨论(0)
提交回复
热议问题