Solution:
#include <stdio.h> /* Using fgets(), scanf(), printf() in this program */
#include <string.h> /* Using strlen() in this program */
int main()
{
struct books
{
char name[100],author[100];
int year,copies;
}book1,book2;
char c;
char read_new_line;
printf("Enter details of first book\n");
if (fgets(book1.name, sizeof(book1.name), stdin) == NULL)
{
fprintf(stderr, "error reading name of book 1\n");
return -1;
}
/* Strip out \n character added by fgets */
book1.name[strlen(book1.name) - 1] ='\0';
if (fgets(book1.author, sizeof(book1.author), stdin) == NULL)
{
fprintf(stderr, "error reading author of book 1\n");
return -1;
}
/* Strip out \n character added by fgets */
book1.author[strlen(book1.author) - 1] ='\0';
scanf("%d %d",&book1.year,&book1.copies);
/* Strip out \n character left out in input stream */
while ((read_new_line = getchar()) != EOF && read_new_line != '\n')
;
printf("Enter details for second book\n");
if (fgets(book2.name, sizeof(book2.name), stdin) == NULL)
{
fprintf(stderr, "error reading name of book 2\n");
return -1;
}
/* Strip out \n character added by fgets */
book2.name[strlen(book2.name) -1 ] = '\0';
if (fgets(book2.author, sizeof(book2.author), stdin) == NULL)
{
fprintf(stderr, "error reading author of book 2\n");
return -1;
}
/* Strip out \n character added by fgets */
book2.author[strlen(book2.author) - 1] ='\0';
scanf("%d %d",&book2.year,&book2.copies);
/* Strip out \n character left out in input stream */
while((c = getchar()) != '\n' && c != EOF)
;
printf("%s\n%s\n%d\n%d\n",book1.name,book1.author,book1.year,book1.copies);
printf("%s\n%s\n%d\n%d\n",book2.name,book2.author,book2.year,book2.copies);
return 0;
}
Observation on code posted in the question:
Lets try to understand why your code is not working:
After the call to scanf from below statement
scanf("%d%d",&book1.year,&book1.copies);
Your input is
3432\n
23\n
scanf reads in 3432 and stores in &book1.year, following \n gets left out in input
stream. Then, second %d discards leading whitespaces (whitespaces in this context includes spaces, tabs, new line, etc.) and reads in 23 and stores that in &book1.copies, following \n gets left out in input stream.
when gets(book2.name) is called \n left out in input stream matches gets() criteria and hence 'empty string' is assigned to book2.name and whatever is meant and user input provided for book2.name is stored in book2.author.
Followed by whatever string meant for book2.author and typed as user input is assigned to book2.year%d conversion is done to that and it fails, as no proper integer entered and scanf() returns failed.
Note :