c++ - 在 Unix 控制台上按下后立即接收 key

标签 c++ linux terminal ros

我正在 Linux 上开发 C++ 程序以将其用作 ROS 节点(有关 ROS 的更多信息)。

Unix 控制台缓冲整行文本,直到用户按下 Enter,但我需要在用户按下键后立即接收击键。

我该怎么做?

我对编写可移植代码不感兴趣。这只是我在大学类(class)的一个事件。

顺便说一句,我运行的是 Ubuntu 16.04.4 LTS,外壳是 bash。

最佳答案

看来你需要一种“无缓冲”的getchar

你应该试试 termios , 例子:

#include <stdio.h>
#include <unistd.h>
#include <termios.h>

int main()
{
    struct termios old_tio, new_tio;
    unsigned char c;

    /* get the terminal settings for stdin */
    tcgetattr(STDIN_FILENO,&old_tio);

    /* we want to keep the old setting to restore them a the end */
    new_tio=old_tio;

    /* disable canonical mode (buffered i/o) and local echo */
    new_tio.c_lflag &=(~ICANON & ~ECHO);

    /* set the new settings immediately */
    tcsetattr(STDIN_FILENO,TCSANOW,&new_tio);

    do {
         c=getchar();
         printf("%d ",c);
    } while(c!='q');

    /* restore the former settings */
    tcsetattr(STDIN_FILENO,TCSANOW,&old_tio);

    return 0;
}

关于c++ - 在 Unix 控制台上按下后立即接收 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50394654/

相关文章:

c++ - 如何访问构造函数 try block 中的对象字段?

基于 C++ 组件的类

linux - 在 Unix 上查找人类可读的文件

linux - 如何使用终端备份文件?

c++ - 我什么时候在 C++ 中使用 const volatile、register volatile、static volatile?

c++ - 使用索引与迭代器将 vector 迭代到倒数第二个元素

linux - Windows docker 容器与 Linux docker 容器

c - 如何获取linux内核的时间戳?

linux - bash 终端 : How do I bind Ctrl+K to kill-whole-line THEN clear screen?

linux - 写入文件 Linux 终端