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

徘徊边缘 提交于 2020-03-06 06:41:11

问题


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.



来源:https://stackoverflow.com/questions/45413808/how-to-use-getch-function-of-c-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!