Results 1 to 4 of 4

Thread: How to Clear Input Buffer

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Contributing Member
    Join Date
    May 2006
    Answers
    75

    How to Clear Input Buffer

    I want to know how to clear the input buffer? Someone tell me the steps for doing the same also enrich my knowledge by putting your ideas on is it necessary that we do it while coding C program


  2. #2
    Contributing Member
    Join Date
    May 2006
    Answers
    82

    Re: How to Clear Input Buffer

    This can be done by using the flush in C programming language.Sometimes it is necessary to forcefully flush a buffer to its stream. In that case this function flush can be used. The general syntax of this function is
    int fflush(FILE *stream);


  3. #3
    Expert Member
    Join Date
    Mar 2012
    Answers
    208

    Re: How to Clear Input Buffer

    fflush(stdin) function can be used to clear the input buffer.
    Without using fflush we can clear the buffer using the code:

    int main(void)
    {
    int ch;
    char buf[BUFSIZ];
    puts("Flushing input");
    while ((ch = getchar()) != '\n' && ch != EOF);
    printf ("Enter some text: ");
    if (fgets(buf, sizeof(buf), stdin))
    {
    printf ("You entered: %s", buf);
    }
    return 0;
    }


  4. #4
    Contributing Member
    Join Date
    Jun 2010
    Answers
    55

    Re: How to Clear Input Buffer

    Contrary to the answers you've gotten so far, you do not want to use fflush to clear an input stream. From the C Language Standard:
    7.19.5.2 The fflush function
    ...
    2 If stream points to an output stream or an update stream in which the most recent
    operation was not input, the fflush function causes any unwritten data for that stream
    to be delivered to the host environment to be written to the file; otherwise, the behavior is
    undefined
    .
    Emphasis mine. Calling fflush on an input stream may clear the stream, or it may not; it may leave the stream in a bad state. Since the behavior is left undefined, the implementation is free to handle the situation any way it wants to. Short answer is, don't use fflush to clear an input stream. Better to read from the stream until you see a newline or EOF character.


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
About us
Applying for a job can be a stressful and frustrating experience, especially for someone who has never done it before. Considering that you are competing for the position with a at least a dozen other applicants, it is imperative that you thoroughly prepare for the job interview, in order to stand a good chance of getting hired. That's where GeekInterview can help.
Interact