1

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.

5
  • Possible duplicate of How do you allow spaces to be entered using scanf? Commented Apr 1, 2017 at 20:39
  • you can use fgets() or getline() or scanf("%[^\n]s",name); Commented Apr 1, 2017 at 20:41
  • I've tried scanf("%[^\n]s", book[*size]._title); and it skips the input altogether. Commented Apr 1, 2017 at 20:45
  • Try this: printf("Title\n"); getchar(); gets(&book[*size]._title); Commented Apr 1, 2017 at 21:27
  • So the scanf reads every character so long as the user does not proceed to newline with enter? Commented Apr 2, 2017 at 0:24

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.