Search code examples
cscanfnewlinefgets

fgets not working properly , not accepting input


I want to take input a string length of 80 but unfortunately it's skipping input. Please suggest how to use fgets() properly, I followed various answer but still not working. I also tried another method with publisher but no luck.

#include<stdio.h>
#define title_max 80
#define publisher_max 20

typedef struct library_book
{
    int id;
    char title[title_max];
    char publisher[publisher_max];
    int code;
    union u
    {
        int no_of_copies;
        char month[10];
        int edition;
    }info;
    int cost;
}book;

int main()
{
    int n;
    printf("\nPlease number of books: ");
    scanf("%d", &n);
    book books[n];
    char title[title_max];
    char publisher[publisher_max];
    for(int i=0;i<n;i++)
    {
        printf("\nPlease enter the ID of the book: ");
        scanf("%d",&books[i].id);
        printf("\nPlease enter the title of the book: ");
        // scanf("%[^\n]%*c",&books[i].title);
        fgets (title,title_max,stdin);
        strcpy(books[i].title, title);
        printf("\nPlease enter the name of publisher: ");
        scanf("%[^\n]%*c",&books[i].publisher);
        
    }

    for(int i=0;i<n;i++)
    {
        printf("\nTitle: %s",books[i].title);
    }
    return 0;
}

Output Console:

bright@goodman:/mnt/d/VS Code/C$ ./a.out

Please number of books: 1

Please enter the ID of the book: 1

Please enter the title of the book: 
Please enter the name of publisher: 123ewdfcads

Please eneter the cost of book: ''123

Please enter the code of the book: 
Title:

Solution

  • The problem is that after preceding call of scanf

        printf("\nPlease enter the ID of the book: ");
        scanf("%d",&books[i].id);
    

    the input buffer contains the new line character '\n' that corresponds to the pressed key Enter.

    So the next call of fgets reads in fact an empty string that contains the new line character from the input buffer.

        fgets (title,title_max,stdin);
    

    You could use the commented call of scanf like

         scanf(" %79[^\n]", books[i].title);
    

    Pay attention to the leading space in the format string. It allows to skip white space characters.

    Also instead of the expression &books[i].title you need to use the expression books[i].title.

    Otherwise before the call of fgets you could insert the following loop

    while ( getchar() != '\n' );
    

    to remove the new line character '\n' from the input buffer.