In general there are two ways to handle cases like this: You can either use char-arrays with a pre-defined size, in which case you must make sure to not write more characters than the array can hold into it. A code with pre-defined sized arrays would look like this:
struct Books {
char title[255];
char author[255];
int pages;
int price;
};
int main()
{
struct Books book;
printf("The title of the book is:\n");
fgets(book.title, sizeof(book.title), stdin);
printf("The title is:\n %s", book.title);
}
In the above case, it's valid to use sizeof(book.title) because the size is known at compile time. But "title" can never exceed 254 characters.
Another way would be using dynamic memory allocation:
struct Books {
char * title;
char * author;
int pages;
int price;
};
int main()
{
struct Books book;
book.title = NULL;
size_t n = 0;
printf("The title of the book is:\n");
getline(&book.title, &n, stdin);
printf("The title is:\n %s", book.title);
free(book.title);
}
In this case, the getline() function allocates the memory for you, so there is no pre-defined maximum size of the string. But you have to free it yourself and also cannot use sizeof() to get the size of the array.