getchar does not stop when using scanf

前端 未结 5 911
傲寒
傲寒 2020-11-27 22:38

I have a difficulty understanding getchar(). In the following program getchar works as expected:

#include 


int mai         


        
5条回答
  •  粉色の甜心
    2020-11-27 22:59

    Whitespace is a delimiter for 5y3 %s format specifier, and newline is regarded as whitespace, so it remains buffered. Console input is normally line oriented, so a subsequent call to getchar() will return immediately because a 'line' remains buffered.

    scanf("%s", command );
    while( getchar() != '\n' ){ /* flush to end of input line */ }
    

    Equally if you use getchar() or %c to get a single character you normally need to flush the line, but in this case the character entered may itself be a newline so you need a slightly different solution:

    scanf("%c", ch );
    while( ch != '\n' && getchar() != '\n' ){ /* flush to end of input line */ }
    

    similarly for getchar():

    ch = getchar();
    while( ch != '\n' && getchar() != '\n' ){ /* flush to end of input line */ }
    

    The sensible thing to do of course is to wrap these solutions into stand-alone specialised input functions that you can reuse and also use as a place to put common input validation and error checking code (as in Daniel Fischer's answer which sensibly checks for EOF - you would normally want to avoid having to duplicate those checks and error handling everywhere).

提交回复
热议问题