【我用C语言写程序】
我想读取一个包含学生姓名、分数和备注的 txt 文件
txt 文件的模式如下所示:
1,Adam Lambert,60,C
2,Josh Roberts,100,A
3,Catherine Zetta,80,B
我想将每个数据分别存储到一个数组中
所以我会有 3 个数组(用于存储 StudentName、Scores 和 Grades)
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
#include <math.h>
char* studName[99];
char* grade[99];
char* grades[100][10];
char buff[1024];
int scores[100];
int score;
int index;
int size;
int index = 0;
int sum = 0;
double average = 0;
int main()
{
FILE *file;
file = fopen("notepad.txt", "r");
if(file == NULL){
printf("Data does not Exist");
}
else {
while(((fgets(buff,1024,file))!=NULL))
{
size = strlen(buff);
buff[size] = 0;
sscanf(buff, "%d, %[^,],%d, %[^,]", &index, studName,&score, grade);
printf("Student Name: %s\n", studName);
printf("Score: %d\n", score);
printf("Remark: %s\n", grade);
scores[index-1] = score;
grades[index-1][10] = grade;
sum+=score;
index++;
}
}
fclose(file);
average = sum/index;
printf("\nThe total score of student is: %d\n", sum);
printf("\nThe sum of student is: %d\n", index);
printf("\nThe average of students' score is: %2f\n", average);
for(int i = 0; i<3; i++){
printf("Score: %d\n", scores[i]);
printf("\nThe Remark is: %s\n", grades[i][10]);
}
getch();
return 0;
}
上面的代码已成功将分数存储在 int 数组中。我的 C 语言不太好,所以我不知道如何存储 StudentName 和 Grades 的 char 数组。
上面的代码给出的成绩存储的结果只是 txt 文件中的最后一个成绩(在本例中为“B”)。
您能告诉我为了实现我的目标我必须解决哪些问题吗?
我的目标基本上是这样的:
StudentName 数组包含 {"Adam Lambert", "Josh Roberts", "Catherine Zetta"}
分数数组包含 {60,100,80}
成绩数组包含 {"C", "A", "B"}
非常感谢。
最佳答案
将螺柱名称和等级从“char *”更改为“char”。您需要一个缓冲区,而不是指针数组。
在顶部添加: char * 学生姓名[100];
设置“分数”和“等级”时添加:
学生姓名[index-1] = strdup(学生姓名);
同时更改以下行中的“10”,数组只有维度 0-9。 成绩[index-1][10] = 成绩;
关于c - 存储数据字符数组C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20365732/