这是源代码,只完成了一部分,本人新手还请见谅
#include<stdio.h>
#include<stdlib.h>
struct library
{
int no= '\0';
char bookname[50]= "\0";
float bookprice= '\0';
struct library *next;
};
//链表长度为len
struct library *creat_link(int len)
{
struct library *head;
struct library *tmp;
int i;
head = (struct library *)malloc(sizeof(struct library));
tmp = head;
for (i = 1; i < len; ++i)
{
head->next = (struct library*)malloc(sizeof(struct library));
head = head->next;
}
head->next = NULL;
return tmp;
}
void read_file_to_link(struct library* head, FILE* fp)
{
if (head == NULL || fp == NULL)
{
fprintf(stderr, "null pointer");//stderr标准输出(设备)文件,对应终端的屏幕,在屏幕上输出null pointer
exit(EXIT_FAILURE);//表示异常退出
}
while (head != NULL)
{
fscanf(fp, "%d% %s %f",&head->no,&head->bookname,&head->bookprice);
head = head->next;
}
}
void print_link(struct library* head)
{
if (head == NULL)
{
fprintf(stderr, "null pointer");//stderr标准输出(设备)文件,对应终端的屏幕,在屏幕上输出null pointer
exit(EXIT_FAILURE);//表示异常退出
}
else
{
printf("编号\t书名\t\t价格\n");
while (head != NULL)
{
printf("%d\t%s\t\t%f\n", head->no, head->bookname, head->bookprice);
head = head->next;
}
}
}
int main()
{
int i = 0, number;
FILE* fp;
char filename[20];
printf("*******欢迎使用图书信息管理系统*******\n");
printf("**********选择想要使用的功能**********\n");
printf("*1.查看所有图书信息 *\n");
printf("*2.查找特定图书的信息 *\n");
printf("*3.对图书信息进行增、删、改 *\n");
printf("**************************************\n");
scanf("%d", &number);
printf("请输入想要使用的文件名\n");
scanf("%s", &filename);
if (number == 1)
{
FILE* fp;
int len; //链表长度
printf("请输入链表的长度\n");
scanf("%d", &len);
fp = fopen(filename, "r");
struct library* head;
head = creat_link(len);
read_file_to_link(head, fp);
print_link(head);
exit(EXIT_SUCCESS);
}
}
需要使用的文本文件里的内容为
1 TheThreeBodyProblem 57
2 HarryPotter 60
3 TwinPeaks 55
4 SherlockHolmes 67
我输出里面的内容就变成这样了
操作越界了。 请看: https://blog.csdn.net/hemeinvyiqiluoben/article/details/79439179