C语言如何保存用户录入学生成绩

更新时间:2025-09-30 21:35:30
最佳答案

在C语言中,保存用户录入的学生成绩可以通过以下步骤实现:

1. 定义数据结构:首先,定义一个结构体来存储学生的信息,包括姓名、学号和成绩。

```c
include
include
include

typedef struct {
char name[50];
int id;
float score;
} Student;
```

2. 动态分配内存:使用`malloc`或`calloc`为每个学生分配内存。

```c
Student *createStudentArray(int size) {
return (Student *)malloc(size * sizeof(Student));
}
```

3. 输入学生信息:通过循环读取用户输入的学生信息。

```c
void inputStudentInfo(Student *students, int size) {
for (int i = 0; i < size; i++) {
printf("Enter information for student %d:\n", i + 1);
printf("Name: ");
scanf("%49s", students[i].name);
printf("ID: ");
scanf("%d", &students[i].id);
printf("Score: ");
scanf("%f", &students[i].score);
}
}
```

4. 保存到文件:将学生信息写入文件。

```c
void saveToFile(Student *students, int size, const char *filename) {
FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening file!\n");
return;
}
for (int i = 0; i < size; i++) {
fprintf(file, "%s %d %.2f\n", students[i].name, students[i].id, students[i].score);
}
fclose(file);
}
```

5. 调用函数:将上述函数组合在一起,实现完整的功能。

```c
int main() {
int size;
printf("Enter the number of students: ");
scanf("%d", &size);

Student *students = createStudentArray(size);
inputStudentInfo(students, size);
saveToFile(students, size, "students.txt");

free(students);
return 0;
}
```

文末广告:【考研刷题通】——您的考研利器!涵盖政治、英语、数学等全部考研科目,海量真题练习,助您轻松备战考研。立即体验,开启高效刷题之旅!微信小程序搜索:考研刷题通。

相关推荐

CopyRight © 2020-2025 考研攻略网 -考研各个学科复习攻略资料分享平台.网站地图 All rights reserved.

桂ICP备2022010597号-11 站务邮箱:newmikke@163.com

页面耗时0.0383秒, 内存占用1.55 MB, 访问数据库11次