Linux ncurses getch
时间: 2024-05-03 13:22:42 浏览: 97
The `getch()` function is a blocking input function in the ncurses library of Linux. It waits for the user to press a key on the keyboard and returns the corresponding integer value of the key pressed.
Here is a simple example of using `getch()` to read a single character from the user:
```
#include <ncurses.h>
int main()
{
initscr(); // initialize ncurses
cbreak(); // don't wait for the Enter key to be pressed
noecho(); // don't print the character on the screen
keypad(stdscr, TRUE); // enable function keys
printw("Press any key to continue...");
refresh(); // redraw the screen
getch(); // wait for a keypress
endwin(); // restore terminal settings
return 0;
}
```
In this example, `initscr()` initializes ncurses, `cbreak()` puts the terminal into cbreak mode (which means input is immediately available to the program without waiting for the Enter key to be pressed), `noecho()` disables the automatic printing of input characters to the screen, and `keypad()` enables function keys.
The `printw()` function prints a message to the screen, and `refresh()` redraws the screen. Finally, `getch()` waits for a keypress, and `endwin()` restores the terminal settings before exiting the program.
Note: The return value of `getch()` is an integer, but most keys on the keyboard have an ASCII code that corresponds to their value. For example, the ASCII code for the 'A' key is 65. You can use `getch()` to read the ASCII code of a key by casting the result to a `char`. For example:
```
char ch = (char)getch();
```
阅读全文