Reputation: 1083
It always displays "hello world". Why?
#include <stdio.h>
int main(void)
{
printf("..... world\rhello\n");
return 0;
}
Upvotes: 1
Views: 563
Reputation: 1627
Using \r
you are returning to the beginning of the current line and're overwriting the dots ".....
":
printf("..... world\rhello\n");
^^^^^ vvvvv
hello <----- hello
How it works:
..... world
^
then returning to the beginning of the current line:
..... world
^
and then printing a word after \r
. The result is:
hello world
^
Upvotes: 4
Reputation:
#include<stdio.h>
#include<conio.h>
int main(void)
{
// You will hear Audible tone 3 times.
printf("The Audible Bell ---> \a\a\a\n");
// \b (backspace) Moves the active position to the
// previous position on the current line.
printf("The Backspace ---> ___ \b\b\b\b\b\b\b\b\b\bTesting\n");
//\n (new line) Moves the active position to the initial
// position of the next line.
printf("The newline ---> \n\n");
//\r (carriage return) Moves the active position to the
// initial position of the current line.
printf("The carriage return ---> \rTesting\rThis program is for testing\n");
// Moves the current position to a tab space position
printf("The horizontal tab ---> \tTesting\t\n");
getch();
return 0;
}
/***************************OUTPUT************************
The Audible Bell --->
The Backspace ---> Testing__
The newline --->
This program is for testing
The horizontal tab ---> Testing
***************************OUTPUT************************/
Upvotes: 0
Reputation: 89
Check it again, it will give out put like
..... world
hello
and what so over you write inside printf() , it will return that as output
Upvotes: 0
Reputation: 354854
This is because \r
is a carriage return (CR). It returns the caret to the start of the line. Afterwards you write hello
there, effectively overwriting the dots.
\n
(line feed, LF) on the other hand used to move the caret just one line downwards, which is why teletypewriters had the sequence CR-LF, or carriage return followed by a line feed to position the caret at the start of the next line. Unix did away with this and LF now does this on its own. CR still exists with its old semantics, though.
Upvotes: 10
Reputation: 400129
Because the lone \r
(carriage return) character is causing your terminal to go back to the beginning of the line, without changing lines. Thus, the characters to the left of the \r
are overwritten by "hello"
.
Upvotes: 2