C语言使用结构体读取文本文件图书记录无预期输出问题求助
图书馆管理程序问题修复方案
核心错误点
- 统计文件行数后文件指针已处于文件末尾,未重置指针就执行读取操作,无法拿到有效数据
- 误用
fread读取文本文件:fread是二进制读写接口,你的lib.txt是制表符分隔的文本文件,需要用fscanf按格式读取字段 - 分馆查询逻辑错误:case 2分支中仍在对比出版社字段,未匹配分馆字段
- 非法调用
fflush(pb):fflush仅支持操作文件流,不能作用于普通内存指针
修复后完整代码
#include <stdio.h> #include <conio.h> #include <stdlib.h> #include <string.h> struct Books { char name[100]; char author[100]; char publisher[100]; double price; char branch[100]; }; typedef struct Books Books; int main() { int a = 0,b=0,ch,i; char *pb = (char *)malloc(100*sizeof(char)); Books *bk; FILE *fp; fp = fopen("lib.txt","r"); if(fp == NULL) { fprintf(stderr,"\n Error to open the file \n"); exit(1); } // 统计行数 char c; while((c = fgetc(fp)) != EOF) { if(c=='\n') { a++; } } a++; // 重置文件指针到开头 rewind(fp); bk = (Books *)malloc(a*sizeof(Books)); // 用fscanf按文本格式读取,%s默认跳过空格、制表符、换行符 while(b < a && fscanf(fp, "%s %s %s %lf %s", bk[b].name, bk[b].author, bk[b].publisher, &bk[b].price, bk[b].branch) == 5) { b++; } // 功能菜单 printf("1. Display books supplied by a particular publisher \n"); printf("2. Display books in a particular branch \n"); printf("3. Exit"); printf("\n"); printf("Enter your choice : "); scanf("%d",&ch); switch(ch) { case 1: { printf("Enter the name of publisher \n"); scanf(" %s",pb); printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n"); for(i=0;i<b;i++) { if(strcmp(bk[i].publisher,pb)==0) { printf("%s\t%s\t%s\t%.2lf\t%s \n",bk[i].name,bk[i].author,bk[i].publisher,bk[i].price,bk[i].branch); } } break; } case 2: { printf("Enter the name of branch \n"); scanf(" %s",pb); printf("\nName\tAuthor\tPublisher\tPrice\tBranch\n"); for(i=0;i<b;i++) { // 修复为对比branch字段 if(strcmp(bk[i].branch,pb)==0) { printf("%s\t%s\t%s\t%.2lf\t%s \n",bk[i].name,bk[i].author,bk[i].publisher,bk[i].price,bk[i].branch); } } break; } case 3: { free(bk); free(pb); fclose(fp); return 0; } default: { printf("Invalid choice"); } } free(bk); free(pb); fclose(fp); getch(); return 0; }
验证说明
代码修复后输入P2可匹配到所有对应出版社的4条记录,输入B1可匹配到对应分馆的1条记录,符合预期功能。
内容的提问来源于stack exchange,提问作者Surya Majumder
相关产品推荐
相关产品推荐

