Hachiman 2015-01-22 07:49 采纳率: 0%
浏览 3629

怎么用fscanf把文件的数据读入链表?

我下面这段代码是哪里出错了? 写入文件没有问题 把文件里的东西写入链表 之后在输出链表 只输出第一行数据 之后都是0
#include "stdio.h"
#include "stdlib.h"
int n=0;
struct stu
{
int num;
char name[100];
float score;
struct stu *next;
};
void str(struct stu *h)
{
while(h!=NULL)
{

printf("%d %s %f\n",h->num,h->name,h->score);
h=h->next;

}
}
void w(struct stu *h)
{
FILE *file;
char fname[100];
int i;
struct stu *pthis,*head,*p1,*p2;
printf("请输入要写入的文件名\n");
scanf("%s",fname);
file=fopen(fname,"w");
if(file==NULL)
{
printf("打开文件错误\n");return;
}
printf("\n\n链表内容将被写入文件\n");
if(h==NULL)
{
printf("错误,没有数据!\n");
return;

}
pthis=h;
while(pthis!=NULL)
{
    fprintf(file,"%d %s %f",pthis->num,pthis->name,pthis->score);
    //fwrite(pthis,sizeof(struct stu),1,file);
    pthis=pthis->next;
}   

fclose(file);
file=fopen(fname,"r");

p1=p2=(struct stu *)malloc(sizeof(struct stu));
fscanf(file,"%d %s %f",&p1->num,p1->name,&p1->score);
head=p1;

//fread(p1,sizeof(struct stu),1,file);
//printf("%d %s %f",p1->num,p1->name,p1->score);
while(n>0)
{
p1=(struct stu *)malloc(sizeof(struct stu));
p2->next=p1;
fscanf(file,"%d %s %f",&p1->num,p1->name,&p1->score);
//p2->next=p1;
p2=p1;
n--;
}
str(head);
fclose(file);

}

main()
{

struct stu *head,*p1,*p2;
head=NULL;
p1=p2=(struct stu *)malloc(sizeof(struct stu));

printf("依次输入学号、姓名、成绩\n"); 
scanf("%d%s%f",&p1->num,p1->name,&p1->score);
head=p1;
while(p1->num!=0)
{
    n++;
    p1=(struct stu *)malloc(sizeof(struct stu));
    printf("依次输入学号、姓名、成绩\n"); 
    scanf("%d%s%f",&p1->num,p1->name,&p1->score);
    p2->next=p1;
    p2=p1;
}

str(head);
fflush(stdin);
w(head); 

}

  • 写回答

2条回答 默认 最新

  • 生命在于奋斗 2015-01-22 09:02
    关注

    代码太乱了,变量命名太随意了。很少有人有耐心给你解决。

    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog