How to use `getch` function of c in Linux?

2019-08-21 09:21发布

问题:

I had installed ncurses library in Linux mint and still I can't use getch function in c. I am using Linux mint 18.2.

Here is my program:

#include <stdio.h>
#include <curses.h>

int main() {
    char k;
    printf("how are you");

    k = getch();
    printf("%c",k);
}

and here is the output:

 ram@ram$ gcc-7 test.c -lcurses
 ram@ram$ ./a.out 
 how are you�ram@ram$

It does't wait for me to press any key and terminate to quickly. I don't want to install conio.h for Linux. How can I use getch and getche function in Linux? Please don't tell me to make my own function. I am still a noob. Or there must be alternatives.

回答1:

Here's a "corrected" version, explaining what's wrong in the comments:

#include <curses.h>
#include <stdio.h>

int main(void)
{
    // use the correct type, see https://linux.die.net/man/3/getch
    int k;

    // init curses:
    initscr();

    // in curses, you have to use curses functions for all terminal I/O
    addstr("How are you?");

    k = getch();

    // end curses:
    endwin();

    printf("You entered %c\n", k);

    return 0;
}

This still isn't good code, you should at least check whether you got a valid character from getch().

It's also important to note that getch() isn't a "function of C". It's part of curses, a well-known platform-independent API for console/terminal control, with implementations e.g. for *nix systems (ncurses) and Windows (pdcurses). It's not part of the language C.