Inserting endline into a stringstream

心不动则不痛 提交于 2019-12-10 14:14:54

问题


We know that when inserting \n in a file stream, the appropriate end-of-line sequence for the system will be written to the file (e.g. \r\n for Windows). Does inserting an endline in a std::stringstream result in the system-appropriate end-of-line sequence being written to the string? For example:

#include <sstream>

int main()
{
    std::ostringstream oss;
    oss << std::endl;
    std::string endlineSequence = oss.str();
    bool isWindows = enlineSequence == "\r\n";
    bool isOldMac  = endlineSequence == "\r";
    bool isUnix    = endlineSequence == "\n";
    // Will this work???
}

回答1:


The system specific line endings are only relevant for text files. As long as the stream is only in memory, it is just '\n'.




回答2:


Short answer: No.

Long answer:

The file stream in text mode will insert a platform specific ELS into the file. But the application will never see this as the ELS is converted back into \n when the file is read. So even with file stream (in text mode) you will never see the ELS.

Back to the std::stringstream. If the code did insert a platform specific ELS (which it does not) then when you read the stream you would still expect to see \n when you read it back as you would expect the ELS to be converted back. There is little point in doing so.



来源:https://stackoverflow.com/questions/6865398/inserting-endline-into-a-stringstream

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