\n(换行符)和\r(回车符)有什么区别?
特别地,\n和\r之间有什么实际的区别吗?是否有应该使用其中一种而不是另一种的地方?
\n(换行符)和\r(回车符)有什么区别?
特别地,\n和\r之间有什么实际的区别吗?是否有应该使用其中一种而不是另一种的地方?
当前回答
不同操作系统的两个不同字符。这在通过TCP/IP传输的数据中也起着作用,这需要使用\r\n。
\ n Unix
\ r Mac
Windows和DOS。
其他回答
不同操作系统的两个不同字符。这在通过TCP/IP传输的数据中也起着作用,这需要使用\r\n。
\ n Unix
\ r Mac
Windows和DOS。
在ascii码方面,它是3——因为它们分别是10和13;-)。
但说真的,有很多:
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;-)
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;-).
\r:回车̲return cr -返回行首回车 \n:换行(n̲ew Line) lf -纸上一行
在屏幕输出的上下文中:
CR:将光标返回到当前行的开头 “LF”:光标下移一行
例如:
你好,\n世界\r!
应该在您的终端上呈现为:
Hello,
! world
一些操作系统可能会破坏预期行为的兼容性,但这不会改变“\n和\r之间的差异?”这个问题的答案。
历史上,a \n用于向下移动车厢,而\r用于将车厢移回页面的左侧。
#include <stdio.h>
void main()
{
int countch=0;
int countwd=1;
printf("Enter your sentence in lowercase: ");
char ch='a';
while(ch!='\r')
{
ch=getche();
if(ch==' ')
countwd++;
else
countch++;
}
printf("\n Words = ",countwd);
printf("Characters = ",countch-1);
getch();
}
让我们以这个例子为例,试着把\n放在\r的地方,它不会工作,并试着猜测为什么?