Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent to getch() & getche() in Linux?

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.

like image 454
Jeegar Patel Avatar asked Sep 19 '11 09:09

Jeegar Patel


People also ask

What can I use instead of getch?

There isn't a direct replacement in standard C++. For getch(), int ch = std::cin. get(); is probably the closest equivalent -- but bear in mind that this will read from buffered standard input, whereas I think the conio.

What is the equivalent of Getch in Java?

There's no getch() function equivalent in java. You have to create a GUI and attach the Event Listener's to them .

Is Getch in conio H?

getch() is a nonstandard function and is present in conio. h header file which is mostly used by MS-DOS compilers like Turbo C. It is not part of the C standard library or ISO C, nor is it defined by POSIX. Like these functions, getch() also reads a single character from the keyboard.

What is getch (); in C?

We use a getch() function in a C/ C++ program to hold the output screen for some time until the user passes a key from the keyboard to exit the console screen. Using getch() function, we can hide the input character provided by the users in the ATM PIN, password, etc.


1 Answers

#include <termios.h> #include <stdio.h>  static struct termios old, current;  /* Initialize new terminal i/o settings */ void initTermios(int echo)  {   tcgetattr(0, &old); /* grab old terminal i/o settings */   current = old; /* make new settings same as old settings */   current.c_lflag &= ~ICANON; /* disable buffered i/o */   if (echo) {       current.c_lflag |= ECHO; /* set echo mode */   } else {       current.c_lflag &= ~ECHO; /* set no echo mode */   }   tcsetattr(0, TCSANOW, &current); /* 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; } 

Output:

(getche example) please type a letter: g You typed: g (getch example) please type a letter... You typed: g 
like image 191
niko Avatar answered Oct 11 '22 11:10

niko