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

后端 未结 12 1687
长发绾君心
长发绾君心 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:06

    On a linux system, you can modify terminal behaviour using the stty command. By default, the terminal will buffer all information until Enter is pressed, before even sending it to the C program.

    A quick, dirty, and not-particularly-portable example to change the behaviour from within the program itself:

    #include
    #include
    
    int main(void){
      int c;
      /* use system call to make terminal send all keystrokes directly to stdin */
      system ("/bin/stty raw");
      while((c=getchar())!= '.') {
        /* type a period to break out of the loop, since CTRL-D won't work raw */
        putchar(c);
      }
      /* use system call to set terminal behaviour to more normal behaviour */
      system ("/bin/stty cooked");
      return 0;
    }
    

    Please note that this isn't really optimal, since it just sort of assumes that stty cooked is the behaviour you want when the program exits, rather than checking what the original terminal settings were. Also, since all special processing is skipped in raw mode, many key sequences (such as CTRL-C or CTRL-D) won't actually work as you expect them to without explicitly processing them in the program.

    You can man stty for more control over the terminal behaviour, depending exactly on what you want to achieve.

提交回复
热议问题