【问题标题】:Move cursor escape sequence移动光标转义序列
【发布时间】:2021-10-16 16:24:19
【问题描述】:

我正在尝试使用转义序列在终端程序中移动光标。在下面的 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
}

【问题讨论】:

  • 每种类型的终端都可以有自己的转义序列。控制终端的一种更便携的方法是使用 curses 库(请参阅 man cursesman ncurses)。

标签: c terminal ansi-escape


【解决方案1】:

您需要拨打fflush:

printf("\033[2;2H"); // move cursor to 2,2
fflush(stdout);
while (1); // keep program running

请注意,while (1); 不是保持程序运行的正确方法,没有sleep 的无限循环将消耗 100% 的 CPU,而是:

while (1) sleep(1); // #include <unistd.h> for sleep()

或者更好:

getchar();

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 2015-09-01
    • 2016-03-28
    • 1970-01-01
    • 2016-01-06
    • 2016-07-18
    • 2013-09-10
    • 1970-01-01
    • 2018-01-27
    相关资源
    最近更新 更多