Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

Clearing stdin in C

Options
  • 12-11-2005 6:34pm
    #1
    Closed Accounts Posts: 4,943 ✭✭✭


    Is there any good way of clearing out any possible characters in the input stream in C? I've seen sites recommend using fflush(stdin) but that doesn't work (other sites have specifically said it won't work, so i'm not surprised). But is there any way of doing this?

    Any ideas would be nice.


Comments

  • Registered Users Posts: 19,396 ✭✭✭✭Karoma


    fflush(stdin) is an undefined behaviour..so no,that's not the way to do it at all.
    one way (It's messy,but then most solutions for this are..)
    while((c = getchar()) != EOF && c != '\n')
    {
    ;
    }

    hmmm,i've never used this but looks cleaner:
    http://www.ee.surrey.ac.uk/Personal/R.Bowden/C/tycpi21d/list14_9.c


  • Closed Accounts Posts: 4,943 ✭✭✭Mutant_Fruit


    Aye, i thought of something like what you wrote, and i've seen it around the place, BUT if there is no characters in stdin, then it will wait for at least one to arrive, wouldn't it? Therefore creating problems... unless you could guarantee there'd be at least one.

    Could you add a letter to stdin in code to avoid the problem of that getchar() stalling while trying to read in a letter when there is nothing in stdin?


Advertisement