需要帮助理解 \n、\b 和 \r 如何呈现 printf 输出
我用 C 语言编写了以下程序,当我运行它时,我对输出感到惊讶。
这是程序
int main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
输出是:- hai 而我期待“absiha”,因为 \n 表示换行,\b 表示退格(非擦除),\r 表示回车。所以我预计 curson 会在“i”字符处,因为 \r 已被应用,但是当我运行它并看到输出时,我感到非常惊讶和困惑。谁能解释一下输出结果吗?
I wrote the following program in the C and when I run it, I was surprised by looking at the output.
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. 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. Can anyone please explain me the output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
让我们一步一步来:
首先,处理退格键。请注意,即使它是“非擦除”,要输出的下一个字符也会覆盖退格的内容:
现在,回车符意味着返回到该行的开头。因此,“ha”会覆盖“asi:
hai
”中的“as” ,现在,光标位于
i
上,因此下一个字符为be 输出将覆盖i
。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:
<new line>hai
Now, the cursor is currently sitting on the
i
, so the next character to be output would overwritei
.访问 http://en.wikipedia.org/wiki/Escape_sequences_in_C
转义序列字符
\a 响铃(扬声器发出蜂鸣声)
\b 退格键(非擦除)
\f 换页/清屏
\n 新行
\r 回车
\t 制表符
\v 垂直制表符
\\ 反斜杠
\?问号
\' 单引号
\" 双引号
\xnn 十六进制字符代码 nn
\onn 八进制字符代码 nn
\nn 八进制字符代码 nn
Visit 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