Why the '\b' at the end of the string doesn't have effect? [duplicate]
Asked Answered
U

2

6

Here is the code below:

#include <stdio.h>

int main(int argc, char* argv[])
{
    printf("WORD\b\b WORD\b\b");
    return 0;
}

which generates this output:

WO WORD

The question is why the last \b does not have effect on the second word more specifically when they are at the end of the string?

Unfrock answered 26/7, 2016 at 12:48 Comment(5)
What OS and terminal are you using?Pesticide
I guess it's because '\b' only moves the cursor back one step, and isn't deleting any characters. The reason 'R' and 'D' is gone from the first 'WORD' is because you're overwritting them with space and 'W'.Corporal
What happens with "WORD\b\b WORD\b\b " ? I suspect your terminal moves the cursor back but does not erase the character.Alburga
@gurka comment seems to be the right answer ! Thanks :)Formicary
I'd argue, that the question is ill-posed. The given program does have the effect of printing the characters to standard output, but it is not in the scope of C or C++ how those characters are interpreted by other parts of the system (for example the terminal showing standard output on the screen).Candycecandystriped
C
5

It does have an affect, the affect is moving the cursor back, but '\b' won't delete any characters unless you overwrite them.

in case you want to print something else afterwards, printing will resume from the current cursor position.

note: this behavior is dependent on the terminal you use to display text.

Crevasse answered 26/7, 2016 at 12:55 Comment(0)
P
2

This depends mainly on the shell / terminal you're using and how it interprets backspace characters.

The behavior you describe above occurs on Windows in a Command Prompt. This terminal apparently moves the cursor back one space on a backspace but does not delete the character. Any characters printed after the backspace overwrite previously written characters.

For example, if you were to do this:

printf("WORD\b\b WORD\b\bx");

Your output would be this:

WO WOxD

In contrast, running your code on a Ubuntu machine under bash results in the following output:

WO WO
Pesticide answered 26/7, 2016 at 12:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.