Why getch() returns before press any key?

前端 未结 2 646
走了就别回头了
走了就别回头了 2020-11-30 10:45
int main(int argc, char *argv[], char *env[])
{
    printf(\"Press any key to exit.\\n\");
    getch();
    return 0;
}

According to the man page,<

2条回答
  •  时光说笑
    2020-11-30 11:15

    Here's a minimal example

    #include 
    
    int main(){
        initscr();
        cbreak();
        noecho();
        printw("Press any key to continue.");
        refresh();
        getch();
        endwin();
        return 0;
    }
    

    But there doesn't seem to be any way to use ncurses without clearing the screen. The Stain of Overkill, perhaps?!

    Edit

    Here's another way I got working. This does not use curses, nor does it clear the screen.

    #include 
    #include 
    #include 
    
    int main() {
        struct termios old,new;
    
        tcgetattr(fileno(stdin),&old);
        tcgetattr(fileno(stdin),&new);
        cfmakeraw(&new);
        tcsetattr(fileno(stdin),TCSANOW,&new);
        fputs("Press any key to continue.",stdout);
        fflush(NULL);
        fgetc(stdin);
        tcsetattr(fileno(stdin),TCSANOW,&old);
    
        return 0;
    }
    

    The manpage says cfmakeraw() might not be fully portable. But it's just a shorthand for setting a whole mess of flags:

    Raw mode
        cfmakeraw() sets the terminal to something like the "raw" mode of the old  Version  7  terminal
        driver:  input  is  available character by character, echoing is disabled, and all special pro-
        cessing of terminal input and output characters is disabled.  The terminal attributes  are  set
        as follows:
    
           termios_p->c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP
                           | INLCR | IGNCR | ICRNL | IXON);
           termios_p->c_oflag &= ~OPOST;
           termios_p->c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
           termios_p->c_cflag &= ~(CSIZE | PARENB);
           termios_p->c_cflag |= CS8;
    

提交回复
热议问题