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

怎么用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 我这模型写的不对吗?为什么lingo解出来的下面影子价格这一溜少一个变量
  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波