【问题标题】:How can I refresh my terminal every second and get user input ?如何每秒刷新终端并获取用户输入?
【发布时间】:2016-01-23 17:55:23
【问题描述】:

我正在尝试在 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。

你知道我该怎么做吗?

【问题讨论】:

    标签: c++ ncurses


    【解决方案1】:

    您需要轮询键盘事件。这可以在 ncurses 中使用getch 完成。

    #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

    【讨论】:

    • 这工作正常,正是我想要的,谢谢!
    • 睡眠一微秒并不是 OP 实际要求的。
    猜你喜欢
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多