0
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct
{
    char* title;
    float price;
} Book;

void Display(Book[], int);

int main()
{
    int n;
    printf("How many books would you like to create?\n");
    scanf("%d", &n);

    Book *books = malloc(n * sizeof(*books));

    if (books == NULL)
    {
        printf("ERROR: Out of memory. \n");
        return 1;
    }

    for (int i = 0; i < n; i++)
    {
        books[i].title = malloc(50);

        if (books[i].title == NULL) {
                printf("No memory\n");
                return 1;
            }

        printf("Please enter a title for book %d\n", (i+1));

        fgets(books[i].title, 50, stdin);

        if ((strlen(books[i].title) > 0) && (books[i].title[strlen (books[i].title) - 1] == '\n'))
            books[i].title[strlen (books[i].title) - 1] = '\0';

        printf("Please enter a price for book %d\n", (i+1));
        scanf("%f", &books[i].price);
    }

    Display(books, n);

    for(int i = 0; i < n; i++)
        free(books[i].title);

    free(books);

    return 0;
}

void Display(Book list[], int size)
{
    for (int i = 0; i < size; i++)
    {
        printf("Title: %s, price: %.2f$. \n", list[i].title, list[i].price);
    }
}

Hey guys I'm trying to pick up C but I've been stuck on this problem for a while. I'm trying to make a program which ask the user how many books he wants and then proceeds to ask for a title (including whitespace) and a price for each book. whenever I run this code, this is the result:

How many books would you like to create?
2
Please enter a title for book 1
Please enter a price for book 1
45.4
Please enter a title for book 2
Please enter a price for book 2
245.6
Title: , price: 45.40$. 
Title: , price: 245.60$.

why does the title input get skipped?

1 Answers1

0

Your problem is this call:

scanf("%d", &n);

Once scanf() finishes parsing the number, it leaves unused input in the buffer. So the newline that the user typed after the number is what your:

fgets(books[i].title, 50, stdin);

gets as input. An empty line. If all your inputs were only fgets() or only scanf() there might be a clean way to deal with this. However, to get you moving forward in your development, you can do:

scanf("%d%*c", &n);
scanf("%f%*c", &books[i].price);

Which will eat the newline for you. However, this is not a complete fix, as the user could type an extra space after the number, and then return, and you're back in the same boat. Just a quick fix to get you moving forward, and then you can go back and address this properly after some research on Google.

cdlane
  • 40,441
  • 5
  • 32
  • 81