I am not able to find the 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.
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
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.
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).
There is a getch() function in the ncurses library. You can get it by installing the ncurses-dev package.
#include <unistd.h>
#include <termios.h>
char getch(void)
{
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 don't want the character to be displayed.
Source: Stackoverflow.com