C getchar vs scanf

前端 未结 3 1669
借酒劲吻你
借酒劲吻你 2020-12-05 01:14

I am confused by a piece of code found in a function I am studying:

char GetCommand( void )
{
    char command;

    do {
        printf( \"Enter command (q=         


        
3条回答
  •  囚心锁ツ
    2020-12-05 02:05

    getchar reads one character from standard input. If you put it in a while loop, it will continue to read one character at a time until the condition is false.

    What the Flush function is doing is reading until it encounters a newline (\n). This is the character produced when the user hits the enter key.

    So, the code you gave will read one character (I'm unclear on why it uses scanf for this instead of simply getchar, which would be faster), and then discards the rest of the input until the user hits enter.

    If you were to feed this program foobar, it would take the f and discard the oobar in the Flush function. Without calling flush, the f could go to one scanf, and the second scanf would get the first o.

提交回复
热议问题