How to clear input buffer in C?

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

    But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character??? Am I misunderstanding something??

    The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.

提交回复
热议问题