#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?