Ant*_*t's 53 c c++ escaping carriage-return
我有这样的C代码:
#include<stdio.h>
int main()
{
printf("Hey this is my first hello world \r");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我使用\r
转义序列作为实验.当我运行代码时,我得到的输出为:
o world
Run Code Online (Sandbox Code Playgroud)
为什么会这样,究竟有什么用\r
?
如果我在在线编译器中运行相同的代码,我得到的输出为:
Hey this is my first hello world
Run Code Online (Sandbox Code Playgroud)
为什么在线编译器产生不同的输出,忽略了\r
?
Arn*_*anc 83
\r
是一个回车人物; 它告诉终端仿真器在行的开头移动光标.
的光标是下一个字符将被呈现的位置.
因此,打印\r
允许覆盖终端仿真器的当前行.
汤姆·齐赫想通为什么你的程序的输出o world
,而\r
在该行的末尾,你后不显示任何信息:
程序退出时,shell会打印命令提示符.终端将其渲染到您离开光标的位置.您的程序将光标留在行的开头,因此命令提示符会部分覆盖您打印的行.这解释了为什么您看到了后面的命令提示符o world
.
您提到的在线编译器只是将原始输出打印到浏览器.浏览器忽略控制字符,因此\r
无效.
请参阅https://en.wikipedia.org/wiki/Carriage_return
以下是一个用法示例\r
:
#include <stdio.h>
#include <unistd.h>
int main()
{
char chars[] = {'-', '\\', '|', '/'};
unsigned int i;
for (i = 0; ; ++i) {
printf("%c\r", chars[i % sizeof(chars)]);
fflush(stdout);
usleep(200000);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它-
\
|
/
在相同位置重复打印字符,以给出|
终端旋转的错觉.
Tom*_*ych 23
程序正在打印"Hey this is my first hello world "
,然后它将光标移回到行的开头.屏幕上的显示效果取决于您的环境.看起来字符串的开头被某些东西覆盖,也许是你的命令行提示符.
\r
将光标移动到行的开头.
换行在不同系统上的管理方式不同.有些只使用\n
(换行,例如Unix),有些使用(\r
例如OS X afaik之前的MacOS)和一些使用\r\n
(例如Windows afaik).
归档时间: |
|
查看次数: |
138453 次 |
最近记录: |