Alternate method for clearing input buffer in c

后端 未结 3 1525
忘掉有多难
忘掉有多难 2021-01-14 23:50

Is there any other method to clear the input buffer in c withut using

  fflush();

or

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


        
相关标签:
3条回答
  • 2021-01-15 00:23

    Using fgets() as suggester @unwind best approach.

    To flush to the end of the line.

    void FlushStdin(void) {
      int ch;
      while(((ch = getchar()) !='\n') && (ch != EOF));
    }
    

    If stdin is all ready flushed to the end-of-line, calling FlushStdin() or other posted scanf(), fgetc() solutions, will flush to the end of the next line.

    Note scanf("%*[^\n]%*1[\n]"); does not work if the next char is '\n'.

    0 讨论(0)
  • 2021-01-15 00:24

    Another method to clear the input buffer(stdin) would be to use

    scanf("%*[^\n]%*1[\n]");
    

    Here,%*[^\n] instructs scanf to scan everything until a new-line character(\n) is found and then discard it.The %1*[\n] tells scanf to scan 1 character including a \n character and discard it also.

    0 讨论(0)
  • 2021-01-15 00:26

    The best solution is to not depend on the input buffer's state so much.

    Read input as whole lines, using fgets(), then parse those. Don't use e.g. scanf() to read individual values, since it interacts with the buffer in annoying ways.

    0 讨论(0)
提交回复
热议问题