C语言 C中的回车?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4638552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:29:46  来源:igfitidea点击:

Carriage return in C?

c

提问by mr_eclair

Output of Following program is : hai

以下程序的输出是: hai

I didn't get how the \rcarriage return works in this program and in real can any one help me out ?

我不明白\r这个程序中的回车是如何工作的,实际上有人可以帮我吗?

#include <stdio.h>
#include<conio.h>

void main()
{
    printf("\nab");
    printf("\bsi");
    printf("\rha");
    _getch();
}

回答by icecrime

From 5.2.2/2 (character display semantics) :

从 5.2.2/2(字符显示语义):

\b(backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

\n(new line) Moves the active position to the initial position of the next line.

\r(carriage return) Moves the active position to the initial position of the current line.

\b( backspace) 将活动位置移动到当前行上的前一个位置。如果活动位置在一条线的初始位置,则显示设备的行为是未指定的。

\n( new line) 将活动位置移动到下一行的初始位置。

\r(回车) 将活动位置移动到当前行的初始位置。

Here, your code produces :

在这里,您的代码生成:

  • <new_line>ab
  • \b: back one character
  • write si: overrides the bwith s(producing asion the second line)
  • \r: back at the beginning of the current line
  • write ha: overrides the first two characters (producing haion the second line)
  • <new_line>ab
  • \b: 返回一个字符
  • write si: 覆盖bwith s(asi在第二行产生)
  • \r: 回到当前行的开头
  • write ha:覆盖前两个字符(hai在第二行产生)

In the end, the output is :

最后,输出是:

\nhai

回答by 0xHenry

Program prints ab, goes back one character and prints sioverwriting the bresulting asi. Carriage return returns the caret to the first column of the current line. That means the hawill be printed over asand the result is hai

程序打印ab,返回一个字符并打印si覆盖b结果asi。回车将插入符返回到当前行的第一列。这意味着ha将被打印出来as,结果是hai

回答by Clifford

Step-by-step:

一步步:

[newline]ab

[换行]ab

ab

[backspace]si

[退格]si

asi

[carriage-return]ha

[回车]ha

hai

Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.

回车,不会导致换行。在某些情况下,单个 CR 或 LF 可以转换为 CR-LF 对。这取决于控制台和/或流。