getchar does not stop when using scanf

前端 未结 5 925
傲寒
傲寒 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 23:11

    The input is only sent to the program after you typed a newline, but

    scanf("%s", command );
    

    leaves the newline in the input buffer, since the %s(1) format stops when the first whitespace character is encountered after some non-whitespace, getchar() then returns that newline immediately and doesn't need to wait for further input.

    Your workaround works because it clears the newline from the input buffer before calling getchar() once more.

    To emulate the behaviour, clear the input buffer before printing the message,

    scanf("%s", command);
    int c;
    do {
        c = getchar();
    }while(c != '\n' && c != EOF);
    if (c == EOF) {
        // input stream ended, do something about it, exit perhaps
    } else {
        printf("Type Enter to continue\n");
        getchar();
    }
    

    (1) Note that using %s in scanf is very unsafe, you should restrict the input to what your buffer can hold with a field-width, scanf("%99s", command) will read at most 99 (sizeof(command) - 1)) characters into command, leaving space for the 0-terminator.

提交回复
热议问题