Reputation: 53
when \b
used inside string.
int main (void)
{
printf("asdfhjk\bll");
return 0;
}
output:
asdfhjll
when \b
used at the end of the string.
int main (void)
{
printf("asdfhjkll\b");
return 0;
}
output:
asdfhjkll
why the last character l
is not removed by \b
. according to the working of \b
, the character preceding the \b
is removed. it works fine when used in the middle of the string, but not when used at the end. why?
Upvotes: 1
Views: 133
Reputation: 37227
The character \b
is a backspace character. It moves the cursor one position backwards without writing any character to the screen.
Consider your first example: asdfhjk\bll
. Before "printing" the backspace character, the screen looks like this:
asdfhjk
^
... where ^
indicates the cursor position. And after printing \b
, it goes this
asdfhjk
^
The the last two characters overwrite k
:
asdfhjll
^
For the second example asdfhjkll\b
. before printing \b
:
asdfhjkll
^
and after:
asdfhjkll
^
No character is erased, but the cursor has been shifted one char backwards. If you print anything else, the last l
gets overridden.
Upvotes: 4
Reputation: 171127
\b
means "move the output position one character backwards." So when you output e.g. x\by
, x
is written, then the output cursor is rewound before the x
just written, and then the y
overwrites the x
.
However, when there's no output following the \b
, the cursor simply remains where it was. Further output would then overwrite the last visible character written.
Upvotes: 1