Flushing Buffer?

This is a discussion on Flushing Buffer? within the C Programming forums, part of the General Programming Boards category; void add_a_book (BOOK book_array[]) { int i=0; /* Search the array for an empty position. An empty position has a ...

  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,796
    >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, 09:07 PM
  2. Need help flushing buffer
    By MSF1981 in forum C Programming
    Replies: 2
    Last Post: 02-15-2009, 06:30 PM
  3. Replies: 16
    Last Post: 10-29-2006, 04: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, 04:15 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21