什么是Linux中的Getch()&getche()?我无法在Linux中找到conio.h的等效头文件。有什么可供选择的吗?getch() & getche()Linux中的函数?我想做一个开关案例基础菜单,用户将提供他的选择,只要按一个键&进程应该向前移动。我不想让用户按回车后,按下他的选择。
3 回答
qq_遁去的一_1
TA贡献1725条经验 获得超7个赞
#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 */ if (echo) { new.c_lflag |= ECHO; /* set echo mode */ } else { new.c_lflag &= ~ECHO; /* set no 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;}
POPMUISE
TA贡献1765条经验 获得超5个赞
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
- 3 回答
- 0 关注
- 800 浏览
添加回答
举报
0/150
提交
取消