使用 fscanf() 读取多个值(如下面的文本文件所示) [英] reading using fscanf() for multiple values (as in the text file below)

查看:30
本文介绍了使用 fscanf() 读取多个值(如下面的文本文件所示)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚接触 fscanf()...请帮助

new to fscanf()...plz help

程序

#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 功能有一些问题...感谢您的帮助...提前致谢

the program is to group the students based on their total into two files...i seem to have some problem though with the fscanf function...ur help with be appreciated...thanks in advance

推荐答案

在没有任何错误的情况下,更难查明问题出在哪里,但这可能与您没有为学生分配内存有关:

Without any errors it is more difficult to pinpoint where you are having problems, but probably it has to do with the fact that you are not allocating memory for you students:

data *students;

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

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

Loading data from file into the allocated memory would look something like

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

当你不再需要它时,不要忘记释放分配的内存

Don't forget to free up the allocate memory after you no longer need it

free(students);

这篇关于使用 fscanf() 读取多个值(如下面的文本文件所示)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆