什么等同于Linux中的getch()&getche()?

我无法在Linux中找到与conio.h等效的头文件。

Linux中有getch()getche()函数吗?

我想做一个切换案例的基本菜单,用户只需按一个键就可以进行选择,并且应该提前执行。 我不想让用户按他的选择后按ENTER键。

 #include <termios.h> #include <stdio.h> static struct termios old, new; /* Initialize new terminal i/o settings */ void initTermios(int echo) { tcgetattr(0, &old); /* grab old terminal i/o settings */ new = old; /* make new settings same as old settings */ new.c_lflag &= ~ICANON; /* disable buffered i/o */ new.c_lflag &= echo ? ECHO : ~ECHO; /* set echo mode */ tcsetattr(0, TCSANOW, &new); /* use these new terminal i/o settings now */ } /* Restore old terminal i/o settings */ void resetTermios(void) { tcsetattr(0, TCSANOW, &old); } /* Read 1 character - echo defines echo mode */ char getch_(int echo) { char ch; initTermios(echo); ch = getchar(); resetTermios(); return ch; } /* Read 1 character without echo */ char getch(void) { return getch_(0); } /* Read 1 character with echo */ char getche(void) { return getch_(1); } /* Let's test it out */ int main(void) { char c; printf("(getche example) please type a letter: "); c = getche(); printf("\nYou typed: %c\n", c); printf("(getch example) please type a letter..."); c = getch(); printf("\nYou typed: %c\n", c); return 0; } 

只需复制这些功能并使用它。 我很久以前就在谷歌上找到了这个代码片段,而且我已经保存了它,最后我在很长一段时间之后为你打开了它!希望它有帮助! 谢谢

 char getch(){ /*#include <unistd.h> //_getch*/ /*#include <termios.h> //_getch*/ char buf=0; struct termios old={0}; fflush(stdout); if(tcgetattr(0, &old)<0) perror("tcsetattr()"); old.c_lflag&=~ICANON; old.c_lflag&=~ECHO; old.c_cc[VMIN]=1; old.c_cc[VTIME]=0; if(tcsetattr(0, TCSANOW, &old)<0) perror("tcsetattr ICANON"); if(read(0,&buf,1)<0) perror("read()"); old.c_lflag|=ICANON; old.c_lflag|=ECHO; if(tcsetattr(0, TCSADRAIN, &old)<0) perror ("tcsetattr ~ICANON"); printf("%c\n",buf); return buf; } 

复制这个功能并使用它, 不要忘记包含

remove the last printf if you dont want the char to be displayed

我建议你使用curses.h或ncurses.h这些实现键盘管理程序,包括getch()。 你有几个选项来改变getch的行为(即等待按键)。

在ncurses库中有一个getch()函数。 你可以通过安装ncurses-dev包得到它。

getch()的替换是在stdio.h声明的getchar()getchar()在Windows和Linux上可用。

在另一个答案中提到的,你可以在linux中使用curses.h库。

您可以通过以下方式在Ubuntu中安装它:

sudo apt-get update

sudo apt-get install ncurses-dev

我从这里拿走了安装部分。

如上所述, getch()ncurses库中。 ncurses必须被初始化 ,看到ie的getchar()返回相同的值(27)的上下箭头键为此