我正在尝试使用ostringstream来构建一个字符串,该字符串使用平台标准的换行符(对于我而言是CRLF,因为我正在开发Windows)。我尝试了以下代码:
std::ostringstream out;
out << "line1\nline2\n";
const char* result = out.str().c_str(); // In result end of lines are '\n' instead
// of the expected '\r\n'
由于ostringstream默认以文本模式打开,我认为它会执行换行符转换(像ofstream一样),但生成的char缓冲区不包含预期的CRLF行尾....
编辑:
对于那些想知道我为什么需要内部的CRLF结尾的人:我将文本复制到Windows剪贴板中,用户经常将该内容复制到记事本中,如果没有CRLF结尾,则在最后一个操作期间丢失行尾....
我的解决方案:
最终,我决定使用boost库将\n替换为\r\n:
boost::replace_all( str, "\n", "\r\n" );
std::ostringstream
使用内部文本字符串表示。CRLF用于磁盘上的文本表示。如果您将std::ifstream
读取为std::string
,则期望将CRLF转换为内部表示。因此,每个人都期望std::string
在任何时刻都包含内部文本表示。 - Serge Dundichboost::replace_all( str, "\n", "\r\n" );
boost::replace_all( str, "\r\n\n", "\r\n" );
- Frank Heimes