问题遇到的现象和发生背景
写将文件中数据导入进链表的函数,使用了fscanf的循环,结果执行到这个循环程序就卡死,反复debug后发现执行完一次fscanf循环后第二次无法开始,如何解决?
问题相关代码,请勿粘贴截图
typedef struct HouseSource //房源的链表
{
char name[20]; //房源名
int price; //房源价格
int start; //起租年份
int end; //退租年份
struct HouseSource next;
} housesource;
void init()
{
FILE fp=NULL;
h1=head_h;
housesource* house=h1;
fp=fopen("./housesource.txt","r");
bool t_repeat;
char t_name[20];
int t_price;
int t_start;
int t_end;
while(!feof(fp))
{
if(fscanf(fp,"%s %d %D %d\n",t_name,&t_price,&t_start,&t_end)==0) //此处大写D是因为csdn不允许重复字符
{
fseek(fp,2,1);
}
else
{
h1=(housesource*)malloc(sizeof(housesource));
strcpy(h1->name,t_name);
h1->price=t_price;
h1->start=t_start;
h1->end=t_end;
h1->next=NULL;
house=(housesource*)malloc(sizeof(housesource));
house->next=h1;
house=h1;
}
}
}
void allocation()
{
head_h=(housesource*)malloc(sizeof(housesource));
head_h->next=NULL;
init();
}
int main()
{
allocation();
return 0;
}
运行结果及报错内容
我的解答思路和尝试过的方法
上网查找了很多关于fscanf函数的内容,试图用fseek跳过,试图改循环判定,均未果,已经束手无策了
我想要达到的结果
循环能完全读取文件中的数据
fscanf(fp,"%s %d %D %d\n",t_name,&t_price,&t_start,&t_end)==0这里应该是 <=0 吧,读取失败返回-1
h1和head_h这两个是全局变量吗?也没看到你声明这两个变量。
建立链表的逻辑也是错误的,代码修改如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct HouseSource //房源的链表
{
char name[20]; //房源名
int price; //房源价格
int start; //起租年份
int end; //退租年份
struct HouseSource* next;
} housesource;
housesource *head_h,*h1;
void init()
{
FILE* fp = NULL;
h1 = head_h;
housesource* house = h1;
fp = fopen("./housesource.txt", "r");
bool t_repeat;
char t_name[20];
int t_price;
int t_start;
int t_end;
while (!feof(fp))
{
if (fscanf(fp, "%s %d %d %d\n", t_name, &t_price, &t_start, &t_end) <= 0) //
{
fseek(fp, 2, 1);
}
else
{
h1 = (housesource*)malloc(sizeof(housesource));
strcpy(h1->name, t_name);
h1->price = t_price;
h1->start = t_start;
h1->end = t_end;
h1->next = NULL;
//house = (housesource*)malloc(sizeof(housesource));
house->next = h1;
house = h1;
}
}
}
void allocation()
{
head_h = (housesource*)malloc(sizeof(housesource));
head_h->next = NULL;
init();
}
int main()
{
allocation();
return 0;
}
您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!