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?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
  • What OS and terminal are you using? – dbush Jul 26 '16 at 12:49
  • 5
    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'. – simon Jul 26 '16 at 12:50
  • 1
    What happens with `"WORD\b\b WORD\b\b "` ? I suspect your terminal moves the cursor back but does not erase the character. – Quentin Jul 26 '16 at 12:50
  • @gurka comment seems to be the right answer ! Thanks :) – Meninx - メネンックス Jul 26 '16 at 12:57
  • 1
    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). – Micha Wiedenmann Jul 26 '16 at 13:02

2 Answers2

4

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.

axiac
  • 68,258
  • 9
  • 99
  • 134
monkeyStix
  • 620
  • 5
  • 10
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
dbush
  • 205,898
  • 23
  • 218
  • 273