Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape sequences are producing unexpected output in C [duplicate]

Tags:

c

I am a beginner in C programming language, recently I have studied about escape sequence.

\n means newline
\b means backspace
\r means carriage-return

When I am applying these on the following program, then I am getting output as hai, Can anyone please explain, how?

main()
{
    printf("\nab");
    printf("\bsi");
    printf("\rha");
}
like image 314
Mayank Tiwari Avatar asked Nov 28 '22 14:11

Mayank Tiwari


2 Answers

\r is actually carriage return (which takes the cursor to the start of the line).

Your program outputs a new line (\n) followed by "ab" then backspace (\b) (over the b) "si", so you now have "asi" on the screen.
The \r takes the cursor to the start of the line and then outputs "ha" leaving "hai" on the screen.

like image 54
noz Avatar answered Dec 16 '22 11:12

noz


The first instruction will print ab on a new line (\n) :

>ab

The second instruction will make a backspace (\b) before printing si :

>asi

Then the last one will make a carriage return (\r) before printing ha :

>hai
like image 23
zakinster Avatar answered Dec 16 '22 10:12

zakinster