gpt4 book ai didi

c - C中的结构体数组

转载 作者:行者123 更新时间:2023-11-30 15:02:50 26 4
gpt4 key购买 nike

我要读取 .ssv 文件并创建一个学生数据库,其中包含:姓名、ID、Exam1、Exam2、Project1、Project2、Average 和 Grade(字母)。平均值不在文件中,因此必须计算它。我不确定我的平均计算和结构声明。任何其他修复都将受到欢迎。

#include <stdio.h>

typedef struct {
char name[26];
int I_D[25];
int exam[3];
int project[3]
float average[3];
char grade[3];
} STUDENT;

void printStuAry(int size, STUDENT stuAry[]);


int main(int argc, char* argv[])
{
if (argc != 2) {
printf("ERROR\n");
return 1;
}

STUDENT stuAry[5];

FILE* f = fopen(argv[1], "r");
if (f == NULL) {
printf("Error opening file %s.\n", argv[1]);
return 1;
}

char line[65];
int ind = 0;
while (fgets(line, sizeof(line), f) != NULL) {
sscanf(line, "%25[^;] ; %d %d %d %d %d %c",
stuAry[ind].name,
&stuAry[ind].I_D,
&stuAry[ind].exam[0],
&stuAry[ind].exam[1],
&stuAry[ind].project[0],
&stuAry[ind].project[1]
&stuAry[ind].grade);


float stuAry.average = stuAry.exam[0] + stuAry.exam[1] + stuAry.project[0] + stuAry.project[1]/4;
ind++;
}
printStuAry(5, stuAry);


if (fclose(f) == EOF) {
printf("Error closing file %s.\n", argv[1]);
return 1;
}

return 0;
}

void printStuAry(int size, STUDENT stuAry[])
{
for (int i=0; i<size; i++) {
printf("Student \"%s\" score %d, %d and %d and %d on midterms, "
"and %c on the final.\n",
stuAry[i].name, stuAry[i].exam[0],
stuAry[i].exam[1], stuAry[i].project[0],
stuAry[i].project[1], stuAry[i].average,
stuAry[i].final);
}
}

最佳答案

我不会为你重写代码,只是指出你的错误。

int I_D[25]; why an array for the id, just an integer

int exam[3];

int project[3]

  • 由于您只有 2 项考试和 2 个项目,因此大小应为 2。
  • 缺少;

float average[3];

char grade[3];

不应该是数组...

while (fgets(line, sizeof(line), f) != NULL) { sscanf(line, "%25[^;] ; %d %d %d %d %d %c", etc...

读取格式良好的文件的正确方法是这样的:

while(7 == fscanf(f, "%25[^;] ; %d %d %d %d %d %c", etc..))

float stuAry.average = stuAry.exam[0] + stuAry.exam[1] + stuAry.project[0] + stuAry.project[1]/4;

  • 将总和括起来
  • 除以 4.0 以避免整数除法并获得具有浮点结果的浮点除法
  • 按 [ind] 对数组进行索引以处理当前学生。

stuAry[ind].average = (stuAry[ind].exam[0] + StuAry[ind].exam[1] + StuAry[ind].project[0] + StuAry[ind].project [1])/4.0;

可能还有其他错误,但这应该会给你一个好的开始

关于c - C中的结构体数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40942468/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com