Max*_*888 3 c terminal ansi-escape
我正在尝试使用转义序列在终端程序中移动光标。在下面的 C 程序中,前三个命令似乎是成功的(清除屏幕、将光标移至主页、打印一些参考文本),但是我尝试将光标移动到任意位置的最后一个命令失败了 (2,2)而是将光标移动到第四行的开头并清除第四行。我究竟做错了什么?
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf("\x1b[2J"); // clear screen
printf("\033[H"); // move cursor home
printf("1111\n2222\n3333\n4444"); // add some text to screen for reference
printf("\033[2;2H"); // move cursor to 2,2
while (1); // keep program running
}
Run Code Online (Sandbox Code Playgroud)
您需要致电fflush:
printf("\033[2;2H"); // move cursor to 2,2
fflush(stdout);
while (1); // keep program running
Run Code Online (Sandbox Code Playgroud)
请注意,这while (1);不是保持程序运行的正确方法,没有 a 的无限循环sleep将消耗 100% 的 CPU,而是:
while (1) sleep(1); // #include <unistd.h> for sleep()
Run Code Online (Sandbox Code Playgroud)
或者更好:
getchar();
Run Code Online (Sandbox Code Playgroud)