2

I am trying to animate a loading bar.

It works completely fine in Windows by doing the following:

    for(int j=0; j<currentSize; ++j)
      cout<<static_cast<char>(219);
    for(int k=maxSize; k>=currentSize; k--)
      cout<<static_cast<char>(177);
    ...
    for(int l = 0; l<maxBarSize; l++){
      cout<<'\b';

When I try in UNIX, however, the backspace command doesn't work. It doesn't delete or print anything. I've also tried using '^H' intead of '\b'.

Is it not possible to erase an output console line in UNIX?

Steven Morad
  • 2,511
  • 3
  • 19
  • 25
  • 5
    try `cout.flush()`. you can use `'\r'` too. note that backspace does not clear anything - only moves the cursor back. – Elazar Jun 01 '13 at 19:50

2 Answers2

3

Have you tried printing [backspace], [space], [backspace]? This will print a space over top the character you're trying to erase.

If that doesn't work, I suspect that the problem lies not in your code, but in your terminal emulator (xterm, etc.) Some support things like backspace, some do not, (and some have it configurable).

Aso, Elazar made the comment about calling cout.flush(). This is becuase most of the time, stdout is line-buffered. That means that the libraries will buffer all data written to stdout until a newline is encountered, at which point the buffer is flushed to the actual file descriptor. By calling flush() you are forcing the output buffer to be written immediately to the file (the TTY).

Community
  • 1
  • 1
Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
3

Printing \b or ^h does just that: it will "print" those characters. It doesn't perform a "back delete" operation, which is what a TTY program would do in response to those as keyboard inputs. You aren't seeing them in the output because they aren't visible characters. They change the cursor position. If you printed:

Hello, World!\b\b\b\b\b\bEarth!

You'd see all those characters if you sent the output to a file. But on a terminal, it might look like:

Hello, Earth!

The "World!" characters are still there, just overwritten by "Earth!"

syam
  • 14,701
  • 3
  • 41
  • 65
lurker
  • 56,987
  • 9
  • 69
  • 103