Jinto
Jinto

Reputation: 179

Using scanf to store string in a structure

I've written a function that stores information on books to a struct Book and everything is working fine except for when the book title has any white spaces. So something like Dracula will be stored and displayed just fine, but something like Lord of the Rings will just skip scanning for the rest of the book's information and proceed to close the program. Is there any way to use scanf to register the string with the white spaces? Here's my code:

void addBook(struct Book book[], int *size)
{
        if(*size== MAX_BOOKS) {
                printf("the inventory is full.\n");
        }

        else {
                printf("ISBN\n");
                scanf("%d", &book[*size]._isbn);
                printf("Title\n");
                scanf("%s", book[*size]._title);
                printf("Price\n");
                scanf("%f", &book[*size]._price);
                printf("Year\n");
                scanf("%d", &book[*size]._year);
                printf("Qty\n");
                scanf("%d", &book[*size]._qty);
                printf("Book successfully added to inventory\n");

                (*size)++;
                }

}

I can update with the full code if necessary.

Upvotes: 1

Views: 1505

Answers (1)

CHillingInTheWooods
CHillingInTheWooods

Reputation: 111

No problem. That's because %s stops at the first space. Use %[^\n] so it reads until he find the enter.

Upvotes: 1

Related Questions