How to clear input buffer in C?

前端 未结 12 2514
一个人的身影
一个人的身影 2020-11-21 08:45

I have the following program:

int main(int argc, char *argv[])
{
  char ch1, ch2;
  printf(\"Input the first character:\"); // Line 1
  scanf(\"%c\", &ch         


        
12条回答
  •  后悔当初
    2020-11-21 09:16

    you can try

    scanf("%c%*c", &ch1);
    

    where %*c accepts and ignores the newline

    one more method instead of fflush(stdin) which invokes undefined behaviour you can write

    while((getchar())!='\n');
    

    don't forget the semicolon after while loop

提交回复
热议问题