Search code examples
cprintfcarriage-return

Why "\r " deletes my previous printed line but "\r" it doesn't


When I print some line, if I want to overwrite for example the first character, I use \r because is the carriage return character but it prints only one character after this one, my whole line is overwritten.

This is some code that I made for this question.

#include <stdio.h>

int main(){

    printf("-------");
    printf("\r ");
    return 0;

}

using this code my output is: with one space.

Now I change a little bit the code. The only change is that in my second printf I delete the space after \r

#include <stdio.h>

int main(){

    printf("-------");
    printf("\r");
    return 0;

}

using this second code my output is "-------" (without quotes)

my expected output: " ------"

Why this is not working?


Solution

  • \r is Carriage Return. It sends the "carriage" (cursor, in modern times) back to the beginning of the same line. It does not by itself erase anything--just moves the cursor. Apparently your terminal has the behavior that printing a character at the beginning of a line erases the rest of the line. That's not guaranteed, I think.

    On many systems if you want to clear the current line you must print \r followed by as many spaces as the line had characters on it.