<分区>
我正在编写一个控制台游戏 (pac-man),我想知道如果用户不按回车键我将如何获得用户输入。我环顾了一下互联网,发现了一些关于 _getch()
的东西,但它显然不再是最新的,并且没有已知的头文件来声明它,除非有人构建自己的头文件,而我不能像我那样做对 C++ 来说仍然是新手。
那么我将如何构建可以执行此操作的代码?
谢谢
<分区>
我正在编写一个控制台游戏 (pac-man),我想知道如果用户不按回车键我将如何获得用户输入。我环顾了一下互联网,发现了一些关于 _getch()
的东西,但它显然不再是最新的,并且没有已知的头文件来声明它,除非有人构建自己的头文件,而我不能像我那样做对 C++ 来说仍然是新手。
那么我将如何构建可以执行此操作的代码?
谢谢
最佳答案
这对我有用(我在 linux 上):
#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++ - 有没有办法在不按回车键的情况下获取用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9547868/