gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:03:42 24 4
gpt4 key购买 nike

我正在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com