简体   繁体   中英

Output backspace character in UNIX

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?

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).

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!"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM