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

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

    Since you are working on a Unix derivative (Ubuntu), here is one way to do it - not recommended, but it will work (as long as you can type commands accurately):

    echo "stty -g $(stty -g)" > restore-sanity
    stty cbreak
    ./your_program
    

    Use interrupt to stop the program when you are bored with it.

    sh restore-sanity
    
    • The 'echo' line saves the current terminal settings as a shell script that will restore them.
    • The 'stty' line turns off most of the special processing (so Control-D has no effect, for example) and sends characters to the program as soon as they are available. It means you cannot edit your typing any more.
    • The 'sh' line reinstates your original terminal settings.

    You can economize if 'stty sane' restores your settings sufficiently accurately for your purposes. The format of '-g' is not portable across versions of 'stty' (so what is generated on Solaris 10 won't work on Linux, or vice versa), but the concept works everywhere. The 'stty sane' option is not universally available, AFAIK (but is on Linux).

提交回复
热议问题