简体   繁体   English

需要帮助了解\\ n,\\ b和\\ r \\ n将如何呈现printf输出

[英]Need help understanding how \n, \b, and \r will render printf output

I wrote the following program in the C and when I run it, I was surprised by looking at the output. 我在C中编写了以下程序,当我运行它时,我惊讶于查看输出。

Here is the program 这是程序

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

The output is :- hai whereas I was expecting "absiha" since \\n is for new line, \\b is for backspace(non erase) and \\r is for carriage return. 输出是: - hai而我期待“absiha”,因为\\ n是新行,\\ b是退格(非擦除),\\ r是回车。 So I was expecting that curson would be at "i" character because \\r has been applied but when I run it and saw the output I was totally surprised and confused. 所以我期待那个光标会处于“i”角色,因为\\ r已经被应用但是当我运行它并看到输出时我感到非常惊讶和困惑。 Can anyone please explain me the output? 有人可以解释一下输出吗?

Let's take it one step at a time: 让我们一步一步:

<new line>ab<backspace>si<carriage return>ha

First, handle the backspace. 首先,处理退格。 Note that even though it is "non-erase", the next character to be output would overwrite what was backspaced over: 请注意,即使它是“非擦除”,要输出的下一个字符也会覆盖退格的内容:

<new line>asi<carriage return>ha

Now, a carriage return means to go back to the beginning of the line. 现在,回车意味着回到行的开头。 So the "ha" overwrites the "as" in "asi: 所以“ha”覆盖了“asi:”中的“as”:

<new line>hai

Now, the cursor is currently sitting on the i , so the next character to be output would overwrite i . 现在,光标当前位于i ,因此要输出的下一个字符将覆盖i

访问http://en.wikipedia.org/wiki/Escape_sequences_in_C

Escape Sequence Character \\a Bell (speaker beeps) \\b Backspace (non-erase) \\f Form feed/clear screen \\n New line \\r Carriage Return \\t Tab \\v Vertical tab \\\\ Backslash \\? Question mark \\' Single quote \\" Double quote \\xnn Hexadecimal character code nn \\onn Octal character code nn \\nn Octal character code nn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM