Wait for user input in C?

前端 未结 3 675
遥遥无期
遥遥无期 2020-12-19 16:49

I\'m trying to make a simple command that pauses for user input. I think it\'ll be useful in Bash scripts.

Here\'s my code:

#include 
         


        
3条回答
  •  鱼传尺愫
    2020-12-19 17:37

    From the GNU C Library Manual:

    Function: char * fgets (char *s, int count, FILE *stream)

    The fgets function reads characters from the stream stream up to and including a newline character and stores them in the string s, adding a null character to mark the end of the string. You must supply count characters worth of space in s, but the number of characters read is at most count − 1. The extra character space is used to hold the null character at the end of the string.

    So, fgets(key,1,stdin); reads 0 characters and returns. (read: immediately)

    Use getchar or getline instead.

    Edit: fgets also doesn't return once count characters are available on the stream, it keeps waiting for a newline and then reads count characters, so "any key" might not be the correct wording in this case then.

    You can use this example to avoid line-buffering:

    #include 
    #include 
    #include 
    
    int mygetch ( void ) 
    {
      int ch;
      struct termios oldt, newt;
      
      tcgetattr ( STDIN_FILENO, &oldt );
      newt = oldt;
      newt.c_lflag &= ~( ICANON | ECHO );
      tcsetattr ( STDIN_FILENO, TCSANOW, &newt );
      ch = getchar();
      tcsetattr ( STDIN_FILENO, TCSANOW, &oldt );
      
      return ch;
    }
    
    int main()
    {
        printf("Press any key to continue.\n");
        mygetch();
        printf("Bye.\n");
    }
    

提交回复
热议问题