How to avoid pressing Enter with getchar() for reading a single character only?

后端 未结 12 1715
长发绾君心
长发绾君心 2020-11-22 00:33

In the next code:

#include 

int main(void) {   
  int c;   
  while ((c=getchar())!= EOF)      
    putchar(c); 
  return 0;
}
12条回答
  •  遥遥无期
    2020-11-22 01:08

    I like Lucas answer, but I would like to elaborate it a bit. There is a built-in function in termios.h named cfmakeraw() which man describes as:

    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 processing of
    terminal input and output characters is disabled. [...]
    

    This basically does the same as what Lucas suggested and more, you can see the exact flags it sets in the man pages: termios(3).

    Use case

    int c = 0;
    static struct termios oldTermios, newTermios;
    
    tcgetattr(STDIN_FILENO, &oldTermios);
    newTermios = oldTermios;
    
    cfmakeraw(&newTermios);
    
    tcsetattr(STDIN_FILENO, TCSANOW, &newTermios);
    c = getchar();
    tcsetattr(STDIN_FILENO, TCSANOW, &oldTermios);
    
    switch (c) {
        case 113: // q
            printf("\n\n");
            exit(0);
            break;
        case 105: // i
            printf("insert\n");
            break;
        default:
            break;
    

提交回复
热议问题