Thread: gets wont work

  1. #1

    Question gets wont work

    void add_book(BOOK database[])
    int i=0;

    while(database[i].number!=0 && i<MAX)

    if (i==MAX)
    printf("There is no more room in the database\n");


    printf("\nBook Number (greater than 0):");

    while (database[i].number <=0);

    printf("\nBook Name:");

    printf("Is this book on loan (y or n)");
    This is a function in my program that adds a book to the database
    When it gets to Book name it skips the gets part and moves on the the nest printf. i cant fix it i have tried everything i know.
    Please help

  2. #2
    Registered User C_Coder's Avatar
    Join Date
    Oct 2001
    *shudders* scanf and gets.

    the scanf is leaving a newline in the input buffer which is picked up by the gets before you enter anything.
    Add this between the scanf and gets:
    while( getchar() != '\n' );
    This will clear the buffer.

    As for the gets, don't ever use it. It will allow the user to overwrite memory, use fgets. fgets allows you to specify the maximum amount of input.
    char name[10];
    printf("Enter name");
    fgets( name, sizeof( name ), stdin );
    Now your user can't enter more characters than you provide storage for.
    fgets also provides an alternative to scanf
    char buffer[20];
    int number;
    printf("Enter number");
    fgets( buffer, sizeof( buffer ), stdin );
    sscanf( buffer, "%d", &number );
    Now you don't need the while( getchar()!='\n);
    Last edited by C_Coder; 03-31-2002 at 02:34 PM.
    All spelling mistakes, syntatical errors and stupid comments are intentional.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  3. Why don't the tutorials on this site work on my computer?
    By jsrig88 in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2006, 10:39 PM
  4. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM