Undo a newline (\n) printed to command line

旧巷老猫 提交于 2019-12-18 04:42:21

问题


printf("Error %d\n", 1);
printf("\nStatus: %d%%", 50);

prints

Error 1

Status: 50%

In this set up, is there any chance to insert Error 2\n between Error 1\n and \nStatus: 50%. I understand that \r and \b can be used to change printed text in the same line (e.g., if there is a single \n between Error 1 and Status: 50%), but can I change text in a previous line?

Thanks!


回答1:


Sorry, you cannot.

But you may issue system calls to clear the whole screen instead, like system("clear") (OS-dependent).

Or use ncurses just as Kos mentioned in the comment.




回答2:


What @Ryan said.

Explanation why: stdout is some abstract stream that doesn't have to be the terminal. It may be a file, a pipe, a socket, a printer, a text to speech device or whatever. In many cases there is no sense to what you asked to do. Hence you need some library that works with the terminal specifically.




回答3:


You could use ANSI Escapesequences to move your "cursor" one line up:

void cursorOnLineUp(void) { printf("\033[1A"); }

Or set it to a specific position:

void setCursor(int column, int row) { printf("\033[%d;%dH", row, column) }

Haven't tried it for C++, but succesfully used it for a simple game in ANSI-C!



来源:https://stackoverflow.com/questions/4531000/undo-a-newline-n-printed-to-command-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!