如何決定在控制台上寫文本的位置? (即:97%98%99%...)

[英]How do I decide where to write text on the console? (ie: 97% 98% 99%…)


I'd like to be able to tell cout where to write some specific text so that, for instance, I can show an increasing percentage that will be "updated" by overwriting it every time it changes.
Something like a Progress: 97% that becomes Progress: 98% and then Progress: 99% all in the same place, possibly without re-processing the whole screen output every time.

我希望能夠告訴cout在哪里寫一些特定的文本,以便,例如,我可以顯示一個增加的百分比,通過在每次更改時覆蓋它來“更新”。像進步一樣:97%變為進度:98%然后進度:99%都在同一個地方,可能無需每次重新處理整個屏幕輸出。

I remember QBasic (from the very old days) having a method specific for this purpose, but it seems I cant find anything more "modern" in C++. Wherever I go, I see people mentioning Curses or other "cursed" libraries that, I'm afraid, would bloat my code with unwanted features and possible holes and malfunctions.
Or worse, they suggest to just flood the output stream with tens or hundreds of \n to "hide the dust under the carpet".

我記得QBasic(從很久以前開始)有一個特定於此目的的方法,但似乎我無法在C ++中找到更“現代”的東西。無論我走到哪里,我都會看到人們提到詛咒或其他“被詛咒”的庫,我擔心,這些庫會使我的代碼膨脹,帶來不必要的功能,可能出現漏洞和故障。或者更糟糕的是,他們建議只用數十或數百個輸出流來“隱藏地毯下的灰塵”。

Another idea that has just come to my mind would be to build some kind of array that stores outputs to be then processed in a looped cout-ish function so that all I have to do is to change the part of the array that I need to, somehow purge the current screen content and re-output it all over again with the modifications. Except this would still require Windows' cursed system library to clear the screen or just Curses; or a \n machine-gun function to hide the former output.

我想到的另一個想法是構建某種存儲輸出的數組,然后在循環的cout-ish函數中處理,這樣我所要做的就是改變我需要的數組部分,以某種方式清除當前屏幕內容,並通過修改重新輸出它。除此之外仍然需要Windows詛咒的系統庫來清除屏幕或只是Curses;或者機器槍功能來隱藏前一個輸出。

Any more elegant and/or C++ standard based viable solution?

任何更優雅和/或基於C ++標准的可行解決方案?

2 个解决方案

#1


3  

Any more elegant and C++ standard based viable solution?

任何更優雅和基於C ++標准的可行解決方案?

Basically no, because as mentioned C++ standard has no notion of your terminals capabilities.

基本上沒有,因為如前所述,C ++標准沒有終端功能的概念。

There's the standard escape character literal '\b' for putting a backspace (position the cursor back within the current line) though. This should work with most available terminal types.

然而,有一個標准的轉義字符文字'\ b'用於放置退格(將光標放回當前行內)。這適用於大多數可用的終端類型。

#2


3  

For the simple code as shown most people would use a simple console output followed by \r. This will move cursor to the left position on the same line on most terminals, so you can print 'on top' of already printed line. This is definitely not C++ standard, but I find it elegant enough.

對於如圖所示的簡單代碼,大多數人會使用簡單的控制台輸出,然后是\ r \ n。這會將光標移動到大多數終端上同一行的左側位置,因此您可以打印已打印行的“在頂部”。這絕對不是C ++標准,但我發現它足夠優雅。


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/01/04/729d5e505b7774d1afd7f98ea371e150.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com