Why does scanf returns control back to the program on pressing Enter key?

前端 未结 2 1195
梦如初夏
梦如初夏 2021-01-22 14:20

I wrote the following program.

void main()
{
   int   *piarrNumber1   = (int *) calloc(1, sizeof(int));
   int   iUserInput      = 0;

   scanf(\"%d\", &iUse         


        
2条回答
  •  心在旅途
    2021-01-22 14:49

    Most OSes buffer keyboard input so that they can process backspaces properly -- the OS keeps input in a buffer and only gives it to the program when Enter is hit.

    Most OSes also provide ways to control this, but the way is different for different OSes. On POSIX systems, the tcsetattr command is used to control this terminal buffering, along with lots of other things. You can read the termios(3) manual page for lots of information about it. You get the behavior you want by setting non-canonical mode:

    #include 
    #include 
        :
    struct termios attr;
    tcgetattr(0, &attr);
    attr.c_lflag &= ~ICANON;
    tcsetattr(0, TCSANOW, &attr);
    

    which causes the OS to send every keystroke to your program immediately (except for a few special ones it intercepts, like ctrl-C), without waiting for Enter, and without processing backspaces either.

    Note that terminal settings are persistent across programs that use the same terminal, so you probably want to save the original settings as of when your program started and restore them before it exits.

提交回复
热议问题