-2

I'm trying to understand the source code from a gist (Console progress bar by DanielSWolf).

He wrote this to show a progress bar in the console while doing some work in the background.

Image of progress bar in work
Ripped off his SO answer here.

There is a line of code which I do not understand (row 68):

// If the new text is shorter than the old one: delete overlapping characters
int overlapCount = currentText.Length - text.Length;
if (overlapCount > 0) {
    outputBuilder.Append(' ', overlapCount);
    outputBuilder.Append('\b', overlapCount);
}

This code is called by his timer handler (which is called each timer tick).

I can't find a purpose for keeping those 5 lines code.
Is this a prevention for a console display bug?

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64
Hille
  • 2,123
  • 22
  • 39

2 Answers2

3

Imagine that the text currently on the console is

|Long, long old text

The text cursor is at the start of the line (indicated by the "|"). You want to replace the text with "New text" (which is a shorter string). You print the new string over the old one, arriving at:

New text|ng old text

with the cursor in the middle and the end of the old text still showing. So you print a number of space characters to overwrite those old characters, ending up with

New text |

Now, depending on what you try to achieve, you may want to move the text cursor back to the end of the text. Moving the text cursor back is accomplished by printing \b (backspace) characters. Printing a backspace character doesn't produce any output on the console, it just moves the cursor back by one character. The result is this:

New text|

Daniel Wolf
  • 12,855
  • 13
  • 54
  • 80
2

It's as the comment suggests: if the new line of text is shorter, you need to delete the overlapping characters so that you don't get something like:

Performing some task... [#########-] 99%

Performing some task... Done.#####-] 99%

Owen Pauling
  • 11,349
  • 20
  • 53
  • 64