Akaash
Akaash

Reputation: 69

"carriage return" returns different ouput

I am trying to understand carriage return(\r). So I have written the code below. If i run the below code, I am getting the output is "go".

Method1:

#include <stdio.h>
int main()
{

        printf("chi\rca\rgo");
        return 0;
}

But if i have tried with "\n", then i am getting the output "goi".

Method 2:

#include <stdio.h>
int main()
{
        printf("chi\rca\rgo\n");
        return 0;
}

What is the error in this?
Can anyone help me ?

Upvotes: 0

Views: 145

Answers (1)

Max Vollmer
Max Vollmer

Reputation: 8598

You should get "goi" in both cases. You can test it here.

Carriage return is literally just that - it returns the carriage, i.e. it goes back to the beginning of the line.

So when you print "chi\rca\rgo", this will happen to the output:

==============================
| 1. | print "chi"     | chi |
==============================
| 2. | carriage return | chi |
==============================
| 3. | print "ca"      | cai |
==============================
| 4. | carriage return | cai |
==============================
| 5. | print "go"      | goi |
==============================

Adding \n at the end of your output doesn't change that behavior. However terminals are often line buffered, meaning that a newline character behaves like a flush. It could be that you only see "go" in the first scenario, because without the newline character the terminal just hasn't printed all characters for that line yet.

Upvotes: 1

Related Questions