如何将此程序从conio移植到curses?

Ves*_*mić 7 c linux curses ncurses conio

我在Windows上写了这个简单的程序.由于Windows有conio,它工作得很好.

#include <stdio.h>
#include <conio.h>

int main()
{
    char input;

    for(;;)
    {
        if(kbhit())
        {
            input = getch();
            printf("%c", input);
        }
    }
}    
Run Code Online (Sandbox Code Playgroud)

现在我想将它移植到Linux,而curses/ncurses似乎是正确的方法.如何使用这些库代替conio来实现同样的目标?

Dmi*_*nko 9

#include <stdio.h>
#include <ncurses.h>

int main(int argc, char *argv)
{
    char input;

    initscr(); // entering ncurses mode
    raw();     // CTRL-C and others do not generate signals
    noecho();  // pressed symbols wont be printed to screen
    cbreak();  // disable line buffering
    while (1) {
        erase();
        mvprintw(1,0, "Enter symbol, please");
        input = getch();
        mvprintw(2,0, "You have entered %c", input);
        getch(); // press any key to continue
    }
    endwin(); // leaving ncurses mode    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

在构建程序时,不要忘记将ncurses lib(-L lncurses)标志链接到gcc

gcc -g -o sample sample.c -L lncurses
Run Code Online (Sandbox Code Playgroud)

在这里,你可以看到的kbhit()实现了Linux操作系统.