使用*两者*回车符和换行符有什么意义?
我本来以为一个就够了。但是,当您可以简单地使用 CR
(0D
) 时,执行 CRLF
(0x0D0A
) 有何意义呢?通常,每当我使用字符串 (C++) 时,我都会这样做:
myString = "Test\nThis should be a new line!\nAnother linefeed.";
注意:对于阅读本文的非 C++ 程序员,"\n"
是换行符 (0x0A
) 。
但我真的应该这样做吗:
myString = "Test\r\nThis should be a new line!\r\nAnother carriage return/linefeed pair.";
注意:"\r"
表示回车符 (0x0D
)。
编辑:这应该在 Programmers.SE 上吗?
I'd have thought one was enough. But what's the point of doing CRLF
(0x0D0A
), when you can simply use CR
(0D
)? Normally, whenever I'm using strings (C++), I do this:
myString = "Test\nThis should be a new line!\nAnother linefeed.";
NOTE: For non-C++ programmers reading this, "\n"
is a linefeed (0x0A
).
But should I really be doing this:
myString = "Test\r\nThis should be a new line!\r\nAnother carriage return/linefeed pair.";
NOTE: "\r"
means carriage return (0x0D
).
EDIT: Should this be on Programmers.SE?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
请记住,这些代码全部来自旧的电传打字机。这些都是有效的打字机:既需要使纸张前进一行(换行),又需要将打印头(在滑架上)返回到纸张的左侧(回车)。
Remember that these codes all came from old Teletype machines. These were effectively typewriters: it was necessary both to advance the paper by a line (line-feed), but also to return the print head (on the carriage) to the left side of the paper (carriage-return).
Windows / Unix / 旧的 Mac 系统在文本文件(不是二进制文件)中写入新行的方式各有不同。如果您在 Windows 下编程,那么在二进制模式下,您将读取(并且您可能想要写入)CRLF 结尾。在类 Unix 系统下,它只是 LF。
如果您处理自己的数据格式...那么您选择哪种方式并不重要。这一切实际上只取决于您想对字符串做什么以及您从哪里获得它。
Windows / Unix / old Mac systems have each different way of writing new lines in text files (not binary ones). If you're programming under windows, then in binary mode, you will read (and you probably want to write) CRLF endings. Under unix-like systems it would be just LF.
If you deal with your own data formats... it shouldn't really matter which way you choose. It all really depends only on what you want to do with the string and where did you get it from.
一些系统(如 UNIX 和 OSX)仅使用换行符,DOS 使用额外的回车符以与电传打字机兼容,Windows 继承了该体系结构。
Some systems like UNIX and OSX just use linefeed, DOS used an additional carriage return in order to be compatible with teletype machines and Windows inherited the architecture.
您可以在 Windows 上使用这两种方法,因为这是 Windows 上的习惯。就是这么简单。但您只能为发往 Windows 的文件编写这两种方法。
You use both on Windows because that's the custom on Windows. It's that simple. But you only write both for files destined for Windows.