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.
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.
There's no getch() function equivalent in java. You have to create a GUI and attach the Event Listener's to them .
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.
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.
#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, ¤t); /* 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With