c语言文件的读入结构体。

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct student{
int num;
char name[25];
float score[6];
}stutype;
typedef struct stu
{
stutype data;
struct stu* next;
}Lstutype;
typedef Lstutype* pstutype;
pstutype a[30];
void main()
{
FILE *fp;
int k,b,m,n;
int i=0,j;
char filename[100];
Lstutype d[30];
printf("该班的人数(最多不超过30个):\n");
scanf("%d",&m);
printf("科目个数(最多不超过6个):\n");
scanf("%d",&n);
for(i=0;i<m;i++)
a[i]=&d[i];
printf("请输入文件名(含扩展名):");
scanf("%s",filename);
while((fp=fopen(filename,"r"))==NULL)
{
printf("can not open file %s\n",filename);
printf("请重新输入文件名(含扩展名):");
scanf("%s",filename);
}
for(i=0;i<m;i++)
{
fscanf(fp,"%s",a[i]->data.name);
fscanf(fp,"%d",&(a[i]->data.num));
for(j=0;j<n;j++)
fscanf(fp,"%6.2f",&(a[i]->data.score[j]));
}
for(i=0;i<m;i++)
{
printf("%s%d",a[i]->data.name,a[i]->data.num);
for(j=0;j<n;j++)
printf("%6.2f",a[i]->data.score[j]);
}
fclose(fp);
}

而文件是这样的:
luo 5 89.00 99.00
cao 6 99.00 54.00

当我输入m为2,n为2时。

为什么输出这样的数据:
luo5-107374176.00-107374176.0089.0099-107374176.00-107374176.00

第1个回答  2013-12-19

#include<stdio.h>

#include<stdlib.h>

#include<string.h>


typedef struct student

{

 int num;

 char name[25];

 float score[6];

}stutype;



typedef struct stu

{

 stutype data;

 struct stu* next;

}Lstutype;


typedef Lstutype* pstutype;

pstutype a[30];



int main()

{

FILE *fp;

int k,b,m,n;

int i,j;

char filename[100];

Lstutype d[30];

    

    i = 0;

    

    printf("该班的人数(最多不超过30个):\n");

scanf("%d",&m);

    printf("科目个数(最多不超过6个):\n");

    scanf("%d",&n);

    

for(i = 0;i < m;i ++)

    {

a[i] = &d[i];

    }

    printf("请输入文件名(含扩展名):");

scanf("%s",filename);

while((fp=fopen(filename,"r"))==NULL)

{

printf("can not open file %s\n",filename);

printf("请重新输入文件名(含扩展名):");

scanf("%s",filename);

}

    

    for(i = 0;i < m; i++)

{

fscanf(fp,"%s",a[i]->data.name);

fscanf(fp,"%d",&(a[i]->data.num));

        //fscanf(fp,"%.2f",&(a[i]->data.score));  //测试用


        for(j = 0;j < n;j++)

        {

//fscanf(fp,"%6.2f",&(a[i]->data.score[j])); 

            fscanf(fp,"%f",&(a[i]->data.score[j]));   //输入这地方的格式符你改下

        }

        

}

    

    for(i = 0;i < m;i++)  // 输出语句

{

printf("%s %d ",a[i]->data.name,a[i]->data.num);

        for(j = 0;j < n;j++)

        {

          printf("%6.2f",a[i]->data.score[j]);

        }

        

        printf("\n");

}

    

    

fclose(fp);

system("pause");

return 0;

}

相似回答