C getchar vs scanf

前端 未结 3 1666
借酒劲吻你
借酒劲吻你 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:07

    getchar() has the side effect of removing the next character from the input buffer. The loop in Flush reads and discards characters until - and including - the newline \n ending the line.

    Since the scanf is told to read one and only one character (%c) this has the effect of ignoring everything else on that input line.

    It would probably be more clear if the scanf was replace with

    command = getchar();
    

    but it's actually a generally bad example as it does not handle End Of File well.

    In general scanf is best forgotten; fgets and sscanf work much better as one is responsible for getting the input and the other for parsing it. scanf (and fscanf) try to do too many jobs at once.

提交回复
热议问题