如何每秒刷新终端并获得用户输入

How can I refresh my terminal every second and get user input ?

本文关键字:用户 输入 何每秒 刷新 终端      更新时间:2023-10-16

我正在尝试在 c++ 中实现 htop(系统单调)。

所以我正在使用 ncurses 来刷新我的终端。

我需要每 5 秒获取一次新信息,例如,im 使用循环来执行此操作。

 while (42)
  {
      key = std::cin.get();
      std::cout << key;
      this->gereEvent(key);
      std::cout << i<< std::endl;
      if (i == 500000000)
      {
          std::cout << "test"<< std::endl;
  //      fputs(tgetstr((char *)"cl", 0), stdout);
        this->refresh();
        i = 0;
      }
      i++;
  }

但问题是cin.get()停止循环。我不能做线程 eithem,因为 std::thread 需要 c++11。

你知道我该怎么做吗?

您需要轮询键盘事件。这可以在带有getch的 ncurses 中完成。

#include<stdio.h>
#include<curses.h>
#include<unistd.h>
int main ()
{
    int i=0;
    initscr();     //in ncurses
    timeout(0);
    while(!i)
    {
        usleep(1);
        i=getch();
        printw("%d ",i);
        if(i>0)
            i=1;
        else
            i=0;
    }
    endwin();
    printf("nhitkb endn");
    return 0;
}

此示例来自 http://cc.byexamples.com/2007/04/08/non-blocking-user-input-in-loop-without-ncurses/comment-page-1/#comment-2100。