要求做一个学生成绩统计管理系统,首先要将学生的信息输入到txt中
但是如果后续要修改信息的化就会很困难
我的想法是将txt中的信息存储到结构体中
比如student[1],student[2],student[3]
想问一样可以实现吗
如果可以的话应该怎么写呢
struct Student
{
int Num;//学号
char Name[20];//姓名
char Sex;//性别
int Age;//年龄
char Banji[100];//班级
float ChineseScore;
float MathScore;
float EnglishScore;
float DataScore;//成绩
float TotalScore;//总分
float Average;//平均分
};
用fscanf从date里面读 然后在用一个for循环依次对应输出
txt文件中的数据按照一定的格式输入是可以实现的,代码参考如下:
struct Student stus[100];
int main(int argc, const char * argv[]) {
FILE *pf;
pf = fopen("student.txt", "r+");
if (pf != NULL) {
int i = 0;
while (!feof(pf)) {
struct Student s;
fscanf(pf, "%d %s %c %d %s %f %f %f %f\n", &s.Num, s.Name, &s.Sex, &s.Age, s.Banji, &s.ChineseScore, &s.MathScore, &s.EnglishScore, &s.DataScore);
// 计算总分和平均分
s.TotalScore = s.ChineseScore + s.MathScore + s.EnglishScore;
s.Average = s.TotalScore / 3;
// 将s存入数组
stus[i] = s;
i++;
}
fclose(pf);
} else {
printf("file is not exist!\n");
}
}
供参考:
#include <stdio.h>
#define N 100
struct Student
{
int Num;//学号
char Name[20];//姓名
char Sex;//性别
int Age;//年龄
char Banji[100];//班级
float ChineseScore;
float MathScore;
float EnglishScore;
float DataScore;//成绩
float TotalScore;//总分
float Average;//平均分
}student[N];
int cnt = 0;
void read_file()
{
FILE* fp;
fp = fopen("studentdata.txt", "r");
if (fp == NULL) {
printf("Open file fail!\n");
return;
}
while (1) {
if (fread(&student[cnt], sizeof(struct Student), 1, fp) != 1) break;
cnt++;
}
fclose(fp);
}
void write_file()
{
int i = 0;
FILE* fp;
fp = fopen("studentdata.txt", "w");
if (fp == NULL) {
printf("Open file fail!\n");
return;
}
while (i < cnt) {
fwrite(&student[i], sizeof(struct Student), 1, fp);
i++;
}
fclose(fp);
}
int main()
{
read_file();
write_file();
return 0;
}