The book_name is picking \n as input a printing the next variable in a new line. I inserted this code while ((getchar()) != '\n');
to prevent fgets() from taking \n as input after using scanf(). But i can't understand why fgets() is taking \n as input. Please explain.
CODE
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
char *book_name;
char *author;
} book;
int main() {
int n;
printf("Enter number of books: \n");
scanf("%d", &n);
book *bk = calloc(n, sizeof(book));
for (int i = 0; i < n; i++)
{
printf("Enter the no of the book: \n");
scanf("%d", &((bk+i)->id));
while ((getchar()) != '\n');
(bk+i)->book_name = malloc(20);
printf("Enter the name of the book: \n");
fgets((bk+i)->book_name, 20, stdin);
(bk+i)->author = malloc(20);
printf("Enter the author of the book: \n");
fgets((bk+i)->author, 20, stdin);
}
for (int i = 0; i < n; i++)
{
printf("%d %s %s\n", (bk+i)->id, (bk+i)->book_name, (bk+i)->author);
}
return 0;
}
OUTPUT