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

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

问题描述

 #include< stdio.h> 
int main()
{
printf(嘿,这是我的第一个hello world \r);
return 0;
}

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

  o world 
pre>

为什么这样,什么是使用 \r



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

 code>嘿,这是我的第一个你好世界

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

解决方案

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



光标是下一个字符将被渲染的位置。



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

汤姆·齐克你知道为什么你的程序的输出是 o wolrd \r 是在该行,然后您不打印任何内容:



当程序退出时,shell打印命令提示符。终端将其显示在您离开光标的位置。您的程序将光标移动到行的开始位置,因此命令提示符部分覆盖您打印的行。这就解释了为什么你看到你的命令提示符后跟 o world



在线编译器你提到只需将原始输出打印到浏览器中。浏览器忽略控制字符,所以 \r 不起作用。



请参阅 https://en.wikipedia.org/wiki/Carriage_return



以下是 \r 的使用示例:

 包括< stdio.h> 
#include< unistd.h>

int main()
{
char chars [] = {' - ','\\','|','/'};
unsigned int i; (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://en.wikipedia.org/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天全站免登陆