什么是'\r'转义序列的使用? [英] What's the Use of '\r' escape sequence?

查看:157
本文介绍了什么是'\r'转义序列的使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的C代码:

 #include< stdio.h> 
int main()
{
printf(Hey this is my first hello world \r);
return 0;
}

我使用了 \r 转义序列作为实验。当我运行代码,我得到的输出为:

  o world 
pre>

为什么, \r 的用途是什么?



如果我在在线编译器中运行相同的代码,我得到输出:

 嘿这是我的第一个hello世界

为什么在线编译器产生不同的输出,忽略 \r

解决方案

\r 是一个回车字符;它会告诉您的终端模拟器将光标移动到行的开头。



光标是下一个字符的显示位置。



因此,打印一个 \r 可以覆盖终端仿真器的当前行。 >

Tom Zych 确定您的程序的输出为什么是 o wolrd ,而 \r 是在该行,并且您之后不打印任何内容:



当程序退出时,shell打印命令提示符。终端将其呈现在您离开游标的地方。您的程序将光标停留在行的开头,因此命令提示符部分覆盖您打印的行。这说明为什么你看到你的命令提示符后面跟着 o world



在线编译器你提到只是打印原始输出到浏览器。浏览器忽略控制字符,因此 \r 无效。



请参阅 https://secure.wikimedia.org/wikipedia/en/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;
}

它重复打印字符 - \ | / 在终端中给出旋转的 | 的错觉。


I have C code like this:

#include<stdio.h>
int main()
{
    printf("Hey this is my first hello world \r");
    return 0;
}

I have used the \r escape sequence as an experiment. When I run the code I get the output as:

o world

Why is that, and what is the use of \r exactly?

If I run the same code in an online compiler I get the output as:

Hey this is my first hello world

Why did the online compiler produce different output, ignoring the \r?

解决方案

\r is a carriage return character; it tells your terminal emulator to move the cursor at the start of the line.

The cursor is the position where the next characters will be rendered.

So, printing a \r allows to override the current line of the terminal emulator.

Tom Zych figured why the output of your program is o wolrd while the \r is at the end of the line and you don't print anything after that:

When your program exits, the shell prints the command prompt. The terminal renders it where you left the cursor. Your program leaves the cursor at the start of the line, so the command prompt partly overrides the line you printed. This explains why you seen your command prompt followed by o world.

The online compiler you mention just prints the raw output to the browser. The browser ignores control characters, so the \r has no effect.

See https://secure.wikimedia.org/wikipedia/en/wiki/Carriage_return

Here is a usage example of \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;
}

It repeatedly prints the characters - \ | / at the same position to give the illusion of a rotating | in the terminal.

这篇关于什么是'\r'转义序列的使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆