0

fscanf() 的新手...请帮助

程序

#include<stdio.h>
typedef struct
{
int rollnum;
char name[30];
int mark1;
int mark2;
int mark3;
}data;

int main(int argc,char* argv[])
{
int total,c1,c2,i;
char str[30];
FILE *original,*pass,*fail;
data *student;

original=fopen("C:\\Users\\user\\Desktop\\struct.txt","r");
pass=fopen("C:\\Users\\user\\Desktop\\pass.txt","w");
fail=fopen("C:\\Users\\user\\Desktop\\fail.txt","w");

for(i=0;i<5;i++)
{
fscanf(original,"%d %s %d %d %d",
&(student+i)->rollnum,
(student+i)->name,
&(student+i)->mark1,
&(student+i)->mark2,
&(student+i)->mark3);
total=student[i].mark1+student[i].mark2+student[i].mark3;
if(total>50)
fprintf(pass,"%d. %s %d\n",c1,student[i].name,total);
else
fprintf(fail,"%d. %s %d\n",c2,student[i].name,total);
c1++,c2++;
}
printf("Successful\n");
fclose(original);
fclose(pass);
fclose(fail);
return 0;
}

**struct.txt**
1 blesswin 20 40 50
2 sam 40 10 20
3 john 50 20 60
4 james 50 40 70
5 peter 10 40 80

该程序是根据学生的总数将学生分组到两个文件中...尽管 fscanf 功能我似乎有一些问题...不胜感激您的帮助...在此先感谢

4

1 回答 1

1

在没有任何错误的情况下,更难确定您遇到问题的地方,但这可能与您没有为学生分配内存的事实有关:

data *students;

students = malloc(number_of_students * sizeof(*students));
if (students==NULL)
    printf("Error: failed to allocate memory\n");

将数据从文件加载到分配的内存中看起来像

for(i=0;i<number_of_students ;i++) {
    fscanf(original,"%d", &(students[i].rollnum));
}

不要忘记在不再需要分配内存后释放它

free(students);
于 2013-10-16T15:36:44.523 回答