\n(换行符)和\r(回车符)有什么区别?

特别地,\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的地方,它不会工作,并试着猜测为什么?

其他回答

\r:回车̲return cr -返回行首回车 \n:换行(n̲ew Line) lf -纸上一行

在屏幕输出的上下文中:

CR:将光标返回到当前行的开头 “LF”:光标下移一行

例如:

你好,\n世界\r!

应该在您的终端上呈现为:

Hello,
!     world

一些操作系统可能会破坏预期行为的兼容性,但这不会改变“\n和\r之间的差异?”这个问题的答案。

两个不同的角色。

\n在Unix文本文件中用作行结束符

\r历史上(在os X之前)在Mac文本文件中用作行结束符

\r\n(即同时使用)用于终止Windows和DOS文本文件中的行。

In windows, the \n moves to the beginning of the next line. The \r moves to the beginning of the current line, without moving to the next line. I have used \r in my own console apps where I am testing out some code and I don't want to see text scrolling up my screen, so rather than use \n after printing out some text, of say, a frame rate (FPS), I will printf("%-10d\r", fps); This will return the cursor to the beginning of the line without moving down to the next line and allow me to have other information on the screen that doesn't get scrolled off while the framerate constantly updates on the same line (the %-10 makes certain the output is at least 10 characters, left justified so it ends up padded by spaces, overwriting any old values for that line). It's quite handy for stuff like this, usually when I have debugging stuff output to my console screen.

一点历史

/r代表返回或回车,它的历史归功于打字机。一个回车符将你的回车符一直向右移动,这样你就在行首输入了。

/n代表新行,同样,从打字的日子开始,你移动到新的行。但不一定要在开头,这就是为什么一些操作系统同时需要/r返回和/n换行符,因为打字机的换行顺序是这样的。这也解释了旧的8位计算机使用Return而不是Enter,从回车中返回,这是很熟悉的。

历史上,a \n用于向下移动车厢,而\r用于将车厢移回页面的左侧。

才能完成,

在shell (bash)脚本中,您可以使用\r发送光标,在行前,当然,\n将光标放在新行上。

例如,试着:

echo -en "AA--AA" ; echo -en "BB" ; echo -en "\rBB"

第一个“回声”显示AA——AA 第二:AA—AABB 最后一个:BB—AABB

但是不要忘记使用-en作为参数。