我怎样才能每秒刷新我的终端并获得用户输入?

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

我正在尝试用 C++ 实现 htop(系统监控)。

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

例如,我需要每 5 秒获取一次新信息,我正在使用循环来这样做。

 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() 停止循环.. 我也不能做一个线程,因为 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 end\n");
    return 0;
}

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