这个问题可能是由于文件中的图书信息没有正确读取导致的。在loadBooksFromFile()函数中,使用fscanf()函数读取文件时,可能存在格式不匹配的问题。

在读取图书信息的时候,可以使用fgets()函数逐行读取文件,并使用sscanf()函数将每行的数据解析到对应的变量中。这样可以确保正确读取每个字段的数据。

修改loadBooksFromFile()函数如下:

void loadBooksFromFile() {
    FILE* file = fopen("books.txt", "r");
    if (file == NULL) {
        printf("文件打开失败\n");
        return;
    }
    
    char line[300];
    
    while (fgets(line, sizeof(line), file) != NULL) {
        char title[100];
        char author[100];
        char code[20];
        char publisher[100];
        int quantity;
        
        sscanf(line, "%s %s %s %s %d", title, author, code, publisher, &quantity);
        
        Book* newBook = (Book*)malloc(sizeof(Book));
        strcpy(newBook->title, title);
        strcpy(newBook->author, author);
        strcpy(newBook->code, code);
        strcpy(newBook->publisher, publisher);
        newBook->quantity = quantity;
        newBook->next = NULL;
        
        if (head == NULL) {
            head = newBook;
        } else {
            Book* current = head;
            while (current->next != NULL) {
                current = current->next;
            }
            current->next = newBook;
        }
    }
    
    fclose(file);
}

这样修改之后,应该能正确读取图书信息并输出。

#include stdioh#include stdlibh#include stringh 定义图书结构体typedef struct Book char title100; char author100; char code20; char publisher100; int quantity; struct Book next; Book; 全局变量指

原文地址: https://www.cveoy.top/t/topic/hKCX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录