How to clear input buffer in C?

前端 未结 12 2369
一个人的身影
一个人的身影 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:07

    Short, portable and declared in stdio.h

    stdin = freopen(NULL,"r",stdin);
    

    Doesn't get hung in an infinite loop when there is nothing on stdin to flush like the following well know line:

    while ((c = getchar()) != '\n' && c != EOF) { }
    

    A little expensive so don't use it in a program that needs to repeatedly clear the buffer.

    Stole from a coworker :)

提交回复
热议问题