How to clear input buffer in C?

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

    A portable way to clear up to the end of a line that you've already tried to read partially is:

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

    This reads and discards characters until it gets \n which signals the end of the file. It also checks against EOF in case the input stream gets closed before the end of the line. The type of c must be int (or larger) in order to be able to hold the value EOF.

    There is no portable way to find out if there are any more lines after the current line (if there aren't, then getchar will block for input).

提交回复
热议问题