How to clear input buffer in C?

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

    The lines:

    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF)
        ;
    

    doesn't read only the characters before the linefeed ('\n'). It reads all the characters in the stream (and discards them) up to and including the next linefeed (or EOF is encountered). For the test to be true, it has to read the linefeed first; so when the loop stops, the linefeed was the last character read, but it has been read.

    As for why it reads a linefeed instead of a carriage return, that's because the system has translated the return to a linefeed. When enter is pressed, that signals the end of the line... but the stream contains a line feed instead since that's the normal end-of-line marker for the system. That might be platform dependent.

    Also, using fflush() on an input stream doesn't work on all platforms; for example it doesn't generally work on Linux.

提交回复
热议问题