Thread: Flushing the input buffer

  1. #1
    ---
    Join Date
    May 2004
    Posts
    1,379

    Flushing the input buffer

    Is there a way to flush the input buffer like this:
    Code:
    while ((ch = getchar()) != '\n' && ch != EOF);
    But without having to hit enter?
    If you do this after calling fgets() you have to hit enter twice. I presented my problem to my instructor yesterday and no surprise he told me to use fflush(stdin). I didn't want to correct him, I just did it so I can pass (lucky for me it worked anyway). But is there another way to do it?

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Not in standard C. Some implementations provide functions to do it (such as fpurge from BSD), but these are non-portable, obviously.

    Also, what is the point of flushing stdin, even if you can? It's just going to annoy/surprise the user, if they are trying to automate a program by piping stuff to its stdin.
    Last edited by cwr; 09-14-2005 at 10:09 PM.

  3. #3
    ---
    Join Date
    May 2004
    Posts
    1,379
    Well, I was calling fgets multiple time to receive data for different fields in a record. If somebody inputs 20 characters when they should only have input 10 then the next call to fgets will use that data that I no longer need.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > If somebody inputs 20 characters when they should only have input 10
    > then the next call to fgets will use that data that I no longer need.
    In that case, you detect whether it is a well-formed record (it has a \n at the end), or whether it is likely garbage because someone is trying to see if they can buffer-overflow your code.

    If the fgets() returns a buffer with a \n, then process it.
    If it doesn't have a \n, throw it away and keep junking input until you find either EOF or a '\n'
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    ---
    Join Date
    May 2004
    Posts
    1,379
    Thanks Salem. Good idea

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. Leaving charscters in input buffer
    By pavlosgr in forum C Programming
    Replies: 5
    Last Post: 11-24-2008, 02:10 PM
  3. How to avoid buffer overflow at input?
    By netstar in forum C++ Programming
    Replies: 4
    Last Post: 02-13-2005, 01:58 AM
  4. How to put a Char into the Input buffer of a console?
    By Aidman in forum C++ Programming
    Replies: 10
    Last Post: 03-09-2003, 10:05 AM