0

This is simple code, when we create a pointer book1 from structure book and then we allocate it memory but when this pointer book1 is passed to the function get_info and when fgets should get value from the user, it simply skips it without taking value using fgets but working perfect with %s.

#include <stdio.h>
#include <stdlib.h>
struct book{
    char title[100];
    char author[100];
};

void get_info (struct book *b1){
    printf("Enter the author: ");
    fgets(b1->author, sizeof(b1->author) , stdin);
    printf("Enter the title: ");
    scanf("%s",b1->title);
}

void display_book (struct book *b1){
    printf("Title: %s\n", b1->title);
    printf("Author: %s\n",b1->author);
}

int main(){
    struct book *book1;
    int n;
    printf("Enter number of book to enter: ");
    scanf("%d",&n);
    book1=(struct book*)malloc(n*sizeof(struct book));
    for (int i=0; i<n; i++){
        get_info(book1+i);
        display_book(book1+i);
    }
    return 0;
}
  • 1
    Mixing `scanf` and `fgets` is tricky. https://stackoverflow.com/questions/5918079/fgets-doesnt-work-after-scanf – Retired Ninja Jun 01 '21 at 07:32
  • 1
    You should not use scanf and fgets. Look at [this question](https://stackoverflow.com/questions/43424781/why-does-scanf-fail-but-fgets-works). – fpiette Jun 01 '21 at 07:43

1 Answers1

0

You code has several issues. You mix scanf and fgets and you forgot that fgets bring the end of line with it.

I fixed it:

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

struct book {
    char title[100];
    char author[100];
};

void get_info(struct book* b1) {
    printf("Enter the author: ");
    fgets(b1->author, sizeof(b1->author), stdin);
    b1->author[strcspn(b1->author, "\r\n")] = 0;   // remove trailing newline
    printf("Enter the title: ");
    fgets(b1->title, sizeof(b1->title), stdin);
    b1->title[strcspn(b1->title, "\r\n")] = 0;     // remove trailing newline
}

void display_book(struct book* b1) {
    printf("Title: %s\n", b1->title);
    printf("Author: %s\n", b1->author);
}

int main() {
    struct book* book1;
    char buf[10];
    int n;
    printf("Enter number of book to enter: ");
    fgets(buf, sizeof(buf), stdin);
    if (sscanf(buf, "%d", &n) != 1) {
        printf("Invalid value entered\n");
        return 1;
    }
   
    book1 = (struct book*)malloc(n * sizeof(struct book));
    for (int i = 0; i < n; i++) {
        get_info(book1 + i);
        display_book(book1 + i);
    }
    return 0;
}
fpiette
  • 11,983
  • 1
  • 24
  • 46