问题描述
\n
(换行符)和\r
(回车符)有什么区别?
What’s the difference between \n
(newline) and \r
(carriage return)?
尤其是\n
和\r
之间是否有实用差异?在某个地方应该使用一个地方而不是另一个地方吗?
In particular, are there any practical differences between \n
and \r
? Are there places where one should be used instead of the other?
推荐答案
就ASCII代码而言,它是3,因为它们分别是10和13;-).
In terms of ascii code, it's 3 -- since they're 10 and 13 respectively;-).
但认真的说,有很多:
- 在Unix和所有类似Unix的系统中,
\n
是行尾代码,\r
没什么特别的 因此, - 在C语言和大多数以某种方式(甚至是远程)复制它的语言中,
\n
是行尾的标准转义序列(根据需要转换为特定于OS的序列/从中转换为特定于OS的序列) - 在旧的Mac系统(OS X之前的版本)中,
\r
代替了行尾代码 - 在Windows(和许多旧版本的操作系统)中,行尾代码按此顺序为2个字符,
\r\n
. - (令人惊讶;-)的后果(回溯到比Windows更早的操作系统),
\r\n
是Internet上文本格式的标准行终止符 - 对于类似于电传打字机的终端",
\r
命令滑架向左返回,直到撞到最左边的挡块(缓慢的操作),\n
命令滚轮向上滚动一行(更快的操作) )-这就是为什么您总是要先\r
\n
,以便滚轮可以在滑架仍向左移动时移动!-)Wikipedia的更多详细说明. - 对于字符模式终端(通常如上所述模拟偶数打印终端),在原始模式下,
\r
和\n
的行为类似(除了在光标方面,因为存在 没有滑架或滚子;-)
- in Unix and all Unix-like systems,
\n
is the code for end-of-line,\r
means nothing special - as a consequence, in C and most languages that somehow copy it (even remotely),
\n
is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed) - in old Mac systems (pre-OS X),
\r
was the code for end-of-line instead - in Windows (and many old OSs), the code for end of line is 2 characters,
\r\n
, in this order - as a (surprising;-) consequence (harking back to OSs much older than Windows),
\r\n
is the standard line-termination for text formats on the Internet - for electromechanical teletype-like "terminals",
\r
commands the carriage to go back leftwards until it hits the leftmost stop (a slow operation),\n
commands the roller to roll up one line (a much faster operation) -- that's the reason you always have\r
before\n
, so that the roller can move while the carriage is still going leftwards!-) Wikipedia has a more detailed explanation. - for character-mode terminals (typically emulating even-older printing ones as above), in raw mode,
\r
and\n
act similarly (except both in terms of the cursor, as there is no carriage or roller;-)
实际上,在现代的写入文本文件的上下文中,您应始终使用\n
(如果您使用的是奇怪的操作系统(例如Windows;-,则底层的运行时将转换为\n
).使用\r
的唯一原因是,如果您正在写一个字符终端(或者更可能是一个模拟它的控制台窗口"),并且希望您写的下一行覆盖您刚写的最后一行(有时用于愚蠢的写法)例如进度条的"ascii动画"效果),尽管如此,但在GUI的世界中这已经变得过时了;-).
In practice, in the modern context of writing to a text file, you should always use \n
(the underlying runtime will translate that if you're on a weird OS, e.g., Windows;-). The only reason to use \r
is if you're writing to a character terminal (or more likely a "console window" emulating it) and want the next line you write to overwrite the last one you just wrote (sometimes used for goofy "ascii animation" effects of e.g. progress bars) -- this is getting pretty obsolete in a world of GUIs, though;-).
这篇关于\ n和\ r之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!