换行符的fgets()逻辑错误

时间:2017-04-15 13:57:09

标签: c newline stdin fgets

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

struct library_catalog
{
    char book_title[100] ;
    char author[100];
    char publisher[100];
    int edition;
    int YOP;
    float price;
};

void getdata(struct library_catalog A[ ], int);
void display(struct library_catalog A[ ], int);

int main()
{
    int n;

    printf("Enter the total number of books : \n");
    scanf("%d", &n);

    struct library_catalog books[n];

    getdata(books, n);
    display(books, n);

    return 0;
}


void getdata( struct library_catalog A[ ], int n)
{
    int i, size;
    char string[50];

    for (i = 0; i < n; i++)
    {   
        int j = i + 1;
        printf("\nFor Book %d            : ", j);

        printf("\nEnter the title of the book:");
        fgets(A[i].book_title, 100, stdin);
        size = strlen(A[i].book_title);
        A[i].book_title[size-1] = '\0';

        printf("\nEnter the author's name: ");
        fgets(A[i].author, 100, stdin);
        size = strlen(A[i].author);
        A[i].author[size-1] = '\0';

        printf("\nEnter the name of the publisher: ");
        fgets(A[i].publisher, 100, stdin);
        size = strlen(A[i].publisher);
        A[i].publisher[size-1] = '\0';

        printf("\nEnter the edition of the book: ");
        scanf("%d", &A[i].edition);

        printf("\nEnter the year of publishing: ");
        scanf("%d", &A[i].YOP);

        printf("\nEnter the price of book: ");
        scanf("%f", &A[i].price);

        size = 0;
    }

    return;

}


void display (struct library_catalog A[ ], int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        int j = i + 1;
        printf("\nBook %d            : ", j);
        printf("\n______________________________________________________________\n");
        printf("\nTitle              : %s", A[i].book_title);
        printf("\nAuthor             : %s", A[i].author);
        printf("\nPublisher          : %s", A[i].publisher);
        printf("\nEdition            : %d", A[i].edition);
        printf("\nYear of Publishing : %d", A[i].YOP);
        printf("\nPrice              : %.2f", A[i].price);
        printf("\n______________________________________________________________\n");
    }

    return;

}

执行后,程序不会读取或扫描(See the program output)书名的名称。我想这与使用太多的字符串输入命令(fgets)有关。这是对的吗?我该如何解决?

0 个答案:

没有答案