What is Equivalent to getch() & getche() in Linux?

2018-12-31 09:45发布

I am not able to find equivalent header file for conio.h in Linux.

Is there any option for getch() & getche() function in Linux?

I want to make a switch case base menu where the user will give his option just by pressing one key & process should be moved ahead. I don't want to let user to press ENTER after pressing his choice.

标签: c linux
7条回答
明月照影归
2楼-- · 2018-12-31 10:06

You can use the curses.h library in linux as mentioned in the other answer.

You can install it in Ubuntu by:

sudo apt-get update

sudo apt-get install ncurses-dev

I took the installation part from here.

查看更多
几人难应
3楼-- · 2018-12-31 10:09
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;
 }

copy this function and use it, dont forget the includes

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

查看更多
梦该遗忘
4楼-- · 2018-12-31 10:20

There is a getch() function in the ncurses library. You can get it by installing the ncurses-dev package.

查看更多
流年柔荑漫光年
5楼-- · 2018-12-31 10:20

The replacement for getch() is getchar() declared in stdio.h. getchar() is available on Windows and Linux.

查看更多
查无此人
6楼-- · 2018-12-31 10:21

As said above getch() is in the ncurses library. ncurses has to be initialized, see i.e. getchar() returns the same value (27) for up and down arrow keys for this

查看更多
不再属于我。
7楼-- · 2018-12-31 10:24

I suggest you use curses.h or ncurses.h these implement keyboard management routines including getch(). You have several options to change the behavior of getch (i.e. wait for keypress or not).

查看更多
登录 后发表回答