Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.
Hi all, please see this major site announcement: https://www.boards.ie/discussion/2058427594/boards-ie-2026

Clearing stdin in C

  • 12-11-2005 05: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, Registered Users 2 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