c-结构数组和文件



实际上,我需要计算学生的课程平均值,例如课程115:成绩分别为86.5和84.3,因此平均值为85.4。因此,我需要从文件中读取数据并将其存储在数组中,但如果不使用file指针之外的指针,我不知道如何做到这一点

文件中有以下数据:studentid、courseid、成绩
输入文件"input.txt":

201456 115 86.5
201456 112 86.4
201456 122 85.4
202145 115 84.3
202145 112 65.3
202145 122 78.4

代码:

#include <stdio.h>
typedef struct{
int courseid;
double courseavg;
} Course;
typedef struct {
int studentid;
double grade[3];
} Student;
typedef struct {
Course course[3];
Student student[2];
} Major;
int main() {
Course course[3] = {
{1, 0.0},
{2, 0.0},
{3, 0.0}
};

Student student[2] = {
{0, 0.0, {0.0, 0.0, 0.0}}, 
{0, 0.0, {0.0, 0.0, 0.0}}
};
FILE *in = fopen("input.txt", "r");
fscanf(in,"%d %d %f %d %d %f %d %d %f %d %d %f %d %d %f %d %d %f",
&student[0].studentid, &course[0].courseid, &student[0].grade[0],
&student[0].studentid, &course[1].courseid, &student[0].grade[1],
&student[0].studentid, &course[2].courseid, &student[0].grade[2],
&student[1].studentid, &course[0].courseid, &student[1].grade[0],
&student[1].studentid, &course[1].courseid, &student[1].grade[1],
&student[1].studentid, &course[2].courseid, &student[1].grade[2]);
course[0].courseavg = (student[0].grade[0] + student[1].grade[0])/2;
printf("%f", &course[0].courseavg);
return 0;
}

您需要逐行读取文件并独立处理每一行:

#include <stdlib.h> // EXIT_FAILURE
#include <stdio.h> // fopen()
#include <stdbool.h> // bool
/**
* Struct that holds evaluation of a student.
*/
struct StudentEvaluation {
int student_id;
int course_id;
float grade;
};
/**
* Function responsible for parsing a single line.
*/
bool processLineBuffer(
const char *line,
struct StudentEvaluation *eval
) {
// sscanf returns the number of items it
// successfully parsed
int ret = sscanf(
line,
"%d %d %f",
&eval->student_id, &eval->course_id, &eval->grade
);
// that's why we check if the return value is 3
return ret == 3;
}
int main(void) {
FILE *fp = fopen("students.txt", "r");
if (!fp) {
fprintf(stderr, "Failed to open file.n");
return EXIT_FAILURE;
}
char line_buffer[256];
while (fgets(line_buffer, sizeof(line_buffer), fp)) {
struct StudentEvaluation eval;
// only examine StudentEvaluation if parsing was successful
if (processLineBuffer(line_buffer, &eval)) {
printf("successfully parsed: n");
// print the parsed data:
printf("    student_id is %dn", eval.student_id);
printf("    course_id is %dn", eval.course_id);
printf("    grade is %fn", eval.grade);
}
}
fclose(fp);
}

这当然不是一个完整的程序,但它应该给你一个框架来(希望(完成你的程序。

最新更新