CRLF 行尾和 ostringstream

发布于 2024-10-27 18:53:28 字数 656 浏览 5 评论 0原文

我正在尝试使用 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" );

I am trying to use a ostringstream to build a string which uses the platform standard line endings (so for me it is CRLF since I am developing for Windows). I tried the following code:

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'

Since ostringstream is opened by default in text mode, I thought it would perform the end of line conversion (like an ofstream) but the resulting char buffer does not contain the expected CRLF end of lines....

Edit:

For those who wondered why I needed the CRLF ending internally: I copy the text into the Windows clipboard and user often copy that content to Notepad and without the CRLF ending the end of lines are lost during that last operation....

My solution:

Finally I decided to use the boost library to replace \n with \r\n:

boost::replace_all( str, "\n", "\r\n" );

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

满栀 2024-11-03 18:53:28

好吧,“\n”行尾的内部表示。

只是当您写入外部文件时,它才会被转换(如果需要!)为外部表示形式。在某些系统上,行结尾只有一个字符,如果使用隐藏长度值存储,则甚至根本没有字符。

Well, '\n' is the internal representation for end-of-line.

It is just when you write to an external file that it is converted (if needed!) to the external representation. On some systems the line ending is just one character, or even no character at all if stored with a hidden length value instead.

神仙妹妹 2024-11-03 18:53:28

文本模式/二进制模式的区别纯粹是 std::filebuf。它不是
其他地方相关。

我不确定为什么你想要内部字符串中除了“\n”之外的任何内容,
但这并不困难:只需定义

char const newline[] = "\x0D\x0A";  //  Or whatever the convention is

并输出即可。

The distinction text mode/binary mode is purely std::filebuf. It's not
relevant elsewhere.

I'm not sure why you would want anything but "\n" in an internal string,
but it's not difficult: just define

char const newline[] = "\x0D\x0A";  //  Or whatever the convention is

and output that.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文