I want to make a more dynamic interface rather than print out a whole new page every time but do not know how to implement it. For example, if we have a download bar that goes from 0% to 100%, I want to change the number directly on the terminal instead of printing out 100 lines with 1%, 2%, 3%. What should I do with it?

有帮助吗?

解决方案

The simpler choice, if you want to keep it on a single line, would be to use \r. Printing \r will move your cursor to the beginning of the line, giving you the ability to print hover the old characters.

A solution would look something like

for (i = 0; i < 100; ++i)
{
    printf("\r%3i%%", i);
    fflush(stdout);
    /* ... */
}

If you need more advanced control over the terminal, you can use termcaps.

其他提示

You could print a \r character, which is called the 'carriage-return' and should in most cases return the cursor to the beginning of the line so you can print over the text that's already there. I say should because it's not guaranteed and it depends on the shell the program is running in. If you want to do more exotic stuff you should look into ncurses.

You should use a cross-platform terminal access library, such as libncurses.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top