gets wont work

This is a discussion on gets wont work within the C Programming forums, part of the General Programming Boards category; void add_book(BOOK database[]) { int i=0; while(database[i].number!=0 && i<MAX) { i++; } if (i==MAX) { printf("There is no more room ...

  1. #1
    Unregistered
    Guest

    Question gets wont work

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

    while(database[i].number!=0 && i<MAX)
    {
    i++;
    }

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

    else

    {
    printf("\nBook Number (greater than 0):");
    do
    scanf("%d",&database[i].number);

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

    printf("\nBook Name:");
    gets(database[i].book_name);


    printf("Is this book on loan (y or n)");
    scanf("%s",&database[i].loan);
    }
    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
    Posts
    523
    *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:
    Code:
    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.
    Code:
    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
    Code:
    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 01: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, 11:39 AM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM

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