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

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

    I've had this problem/question come up in an assignment that I'm currently working on. It also depends on which input you are grabbing from. I am using

    /dev/tty
    

    to get input while the program is running, so that needs to be the filestream associated with the command.

    On the ubuntu machine I have to test/target, it required more than just

    system( "stty -raw" );
    

    or

    system( "stty -icanon" );
    

    I had to add the --file flag, as well as path to the command, like so:

    system( "/bin/stty --file=/dev/tty -icanon" );
    

    Everything is copacetic now.

提交回复
热议问题