2

A backspace escape character in a C string at end of a string before a newline is ignored (in Mac OS X terminal).

printf("hello, worl\bd"); // => hello word (OK)
printf("hello, world\b"); // => hello worl (OK)
printf("hello, world\b\n"); // => hello world\n (Why not hello worl\n ?)

Why is this the case?

Anand
  • 3,690
  • 4
  • 33
  • 64
  • 4
    For the best explanation, look here: http://stackoverflow.com/a/6792880/2710409 – Sarima Sep 10 '14 at 07:09
  • @Joshpbarron - thanks for the link - I understand the behavior in that link's example, but in my example, last line, the existence of \b seems to have no effect - shouldn't it be either of "hello, worl\nd" or "hello, worl\n"? – Anand Sep 10 '14 at 07:43
  • This has been explained in an actual answer, but just for completeness: \b moves the cursor backwards one char, but doesnt write anything. The new line then moves down one line. I can't test this at the moment, but if you used \r instead of \n, you may lose the d as you expect. – Sarima Sep 10 '14 at 08:41
  • @Joshpbarron : Using \r instead of \n deletes (i.e, does not output) the entire string. – Anand Sep 10 '14 at 09:04

2 Answers2

3

If you used \n\b, it would be free to do as it pleased. As it stands, it may be open to more question. C99, §5.2.2/2 Character Display Semantics:

\b (backspace) Moves the active position to the previous position on the current line. If the active position is at the initial position of a line, the behavior of the display device is unspecified.

Since it only specifies moving the "active position", I guess it's not actually obliged to erase anything though.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
1

The \b will only move the cursor back one char but not remove the char there. And printf will print out whatever you have from beginning to where the current cursor is.

NonStatic
  • 951
  • 1
  • 8
  • 27
  • printf will print more than what's up to the cursor, "hello world" is already printed, as the the \b occurs, the cursor is moved in front of the last 'd'. After that a newline is written, which moves the cursor to the beginning of the next line, but the last 'd' on the previous line is already written to the previous line -(it isn't moved to the next line, only the cursor is.) – nos Sep 10 '14 at 07:19
  • @nos, I mean the same thing here. The cursor has been moved to the next line, then everything above next line will be printed out. – NonStatic Sep 10 '14 at 07:22