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++ - 可变模板类中的模板方法

linux - 查找 .emacs 文件 Fedora 20

c - Linux: sockaddr_storage 怎么初始化呢?

php - 64 位 Linux/Ubuntu 和 openssl 问题(无法读取符号 : Bad value)

显示 2 个用户的终端 MAC OSX 正常运行时间命令

c++ - 将规则生成绑定(bind)到我的结构成员时出现编译错误

c++ - 从目录 C++ 打开多个文件

c++ - 数组不接受完整数字

linux - 在 Linux 终端中,破折号是否可以用作临时文件名?

linux - 终端 : Is there any way to print the file names located in specific directory?