Search code examples
cprintfscanfgetsputs

C Struct Array Input


I have the following struct

typedef char String[256];

typedef struct
{
    String name;
    int year;
    float price;
} Book;

Array of Books

int main(int argc, const char * argv[])
{    
    Book books[5];

    for (int i=0; i<5; i++) {
        books[i] = inputBook();
    }

    return 0;
}

inputBook() function

Book inputBook()
{
    Book myBook;

    //Name
    puts("Enter Book Name:");
    gets(myBook.name);

    //Publishing Year
    puts("Enter Book Publishing Year:");
    scanf("%i", &myBook.year);

    //Price
    puts("Enter Book Price:");
    scanf("%f", &myBook.price);

    return myBook;
}

For some reason the first book input is going well but when trying to input the second book and the second call to inputBook() I can set a book name, it jumps straight to the year import.

What is the problem ?

Thanks!


Solution

  • To correct, replace:

    gets(myBook.name);
    

    with:

    scanf("%255s", myBook.name); /* 255 as name is 256 chars. */
    

    as scanf() will skip any whitespace characters, but gets() will not. A newline character is considered a whitespace character and there will be a newline remaining in stdin after the price has been entered causing gets() to read the newline and effectively read nothing.

    Worth reading: warning:gets function is dangerous