I wrote the following program in the C and when I run it, I was surprised by looking at the output.
Here is the program
int main()
{
printf("\nab");
printf("\bsi");
printf("\rha");
}
The output is :- hai
whereas I was expecting “absiha” since \n is for new line, \b is for backspace(non erase) and \r is for carriage return. So I was expecting that curson would be at “i” character because \r has been applied but when I run it and saw the output I was totally surprised and confused. Can anyone please explain me the output?
Let’s take it one step at a time:
<new line>ab<backspace>si<carriage return>haFirst, handle the backspace. Note that even though it is “non-erase”, the next character to be output would overwrite what was backspaced over:
<new line>asi<carriage return>haNow, a carriage return means to go back to the beginning of the line. So the “ha” overwrites the “as” in “asi:
<new line>haiNow, the cursor is currently sitting on the
i, so the next character to be output would overwritei.