Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

c++ - What's the Use of ' ' escape sequence?

I have C code like this:

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

I have used the 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 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 allows to override the current line of the terminal emulator.

Tom Zych figured why the output of your program is o world while the 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 has no effect.

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

Here is a usage example of :

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

int main()
{
        char chars[] = {'-', '\', '|', '/'};
        unsigned int i;

        for (i = 0; ; ++i) {
                printf("%c
", 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...