Thread: Flushing Buffer?

  1. #1
    Registered User
    Join Date
    Oct 2001
    Posts
    44

    Flushing Buffer?

    void add_a_book (BOOK book_array[])
    {



    int i=0;

    /* Search the array for an empty position.
    An empty position has a 0 for the book number */
    while ( book_array[i].number != 0 && i < SIZE )
    i++;

    if ( i == SIZE )
    printf("\nSorry, the database is full\n");
    else /* Add the books details to the database. */
    {
    printf( "\f\nBook Number (1 to 3 digits, except 0) : " );
    do
    scanf( "%3d",&book_array[i].number );
    while (book_array[i].number <= 0 );

    printf("\nBook Name (Maximum 30 characters) : " );
    scanf("%s",&book_array[i].name );

    //printf("\nBook Status (Y)es or (N)o : " );
    //scanf("%c",&book_array[i].status );

    }
    }

    how would i go about flushing the buffer after the second scanf and why is this a problem?
    Dangerous Dave

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >how would i go about flushing the buffer after the second scanf
    The most effective way is
    while ( getchar() != '\n' );

    This will read all remaining input from the stream and discard it.

    >and why is this a problem?
    Because scanf is lame. What happens is when you enter input, scanf will read what you tell it to, but if there is anything else in the stream that matches the next call to scanf, it will read that immediately, not promting the user for input. Such is the case with string input for scanf, usually the culprit is a newline character that scanf leaves in the input stream. The next call reads the newline and quits because scanf is delimited by a newline and whitespace when reading string data.

    -Prelude
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Flushing buffer
    By $l4xklynx in forum C Programming
    Replies: 6
    Last Post: 03-04-2009, 10:07 PM
  2. Need help flushing buffer
    By MSF1981 in forum C Programming
    Replies: 2
    Last Post: 02-15-2009, 07:30 PM
  3. Replies: 16
    Last Post: 10-29-2006, 05:04 AM
  4. buffer contents swapping
    By daluu in forum C++ Programming
    Replies: 7
    Last Post: 10-14-2004, 02:34 PM
  5. Console Screen Buffer
    By GaPe in forum Windows Programming
    Replies: 0
    Last Post: 02-06-2003, 05:15 AM