简体   繁体   中英

Update and multiple console windows

I want to write a simple c++/c console app, to show my process 1% 2%. for now, i print it line by line like

finished 1%
finished 2%

and etc

How can I just update percentage x% without printing a new line?

Also, I want to open two console windows one show messages one show the process as above. How do I open another console window?

On most-all terminals, you can print the ASCII carriage return '\\r' (value 13 decimal) to return the cursor to the left of the current line, allowing you to overwrite the previous value. Or, you can send backspaces ('\\b', ASCII 8) to move a single character left. Neither will automatically remove content already displayed, but you can always overwrite anything you no longer want to see with some spaces. Alternatively, you can use control codes supported by your particular console (eg vt100, vt220...), which will probably have more advanced features such as "clear-to-end-of-line". Many libraries are available to detect the terminal type and use codes it supports, or synthesize advanced operations from many simpler ones where necessary: on Linux and UNIX, the ncurses library is a good choice.

C++ has no concept of console windows. Opening a second window depends a lot on the operating system you're using, and perhaps the graphics library, neither of which you specified. On any OS though, you can have your application write some messages into a file, then inspect that file from another window that you open yourself. On Linux/UNIX, the utility "less" is great for inspecting log files - as well as showing you the contents at the time you ran less, you can ask it to "follow" new data as it is written into the file.

On windows you can move the cursor to any location on the screen, then start printing from there:

COORD c;
c.X = x; c.Y = y;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), c);

Of course, you need to include windows.h

You can update your progress message in several ways. You can print out backspace characters to move the cursor to the left and then write over the old output. If your console supports ANSI escape sequences, you can use an escape sequence to blank out the line and re-draw it.

The best technique to use will probably depend on the console you are using (different consoles support different things). What platform are you using, and what console?

It seems that you're talking about Windows console apps.

Each Windows process is associated with at most one console window.

It you want two console windows then you can start another process and pipe output to it, or communicate with it via sockets or Windows "mailslots" or whatever.

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