Moving the cursor to the beginning of the current line

和自甴很熟 提交于 2021-01-18 05:36:26

问题


I want to print current time (by using printf) in same place, but i want to do it in infinite loop eg:

while(1) {printf("Date and Time are %s", asctime(localtime(&current))); } 

. So before i use printf i should move cursor backward to its staring position. How to do it ?

thx in advance


回答1:


For simply moving the cursor to the beginning of the current line, you may print "\r", which does just that. Notice that it does not erase the old text, so be careful to either overwrite it or to clear with an ANSI code.

On systems using ANSI/VT control codes, you can print "\033[1;2H" to position the cursor. It will move the cursor and will not print anything on screen. The values 1 and 2 are the row and the column, so change them to use different positions.

There are also other codes for colors and other things: http://bluesock.org/~willg/dev/ansi.html

Notice that none of these codes are portable and they may not work on all systems (most notably they don't work by default on some Microsoft systems). Non-supporting systems will instead display some garbage on screen (the code itself).




回答2:


write a \r

while(1) {
 printf("\rDate and Time are %s      ", asctime(localtime(&current)) );
 fflush(stdout);
}



回答3:


It might work to print a "\r" at the start of the line.



来源:https://stackoverflow.com/questions/2386923/moving-the-cursor-to-the-beginning-of-the-current-line

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