用c语言写一个学生学籍管理系统
时间: 2023-05-20 21:05:42 浏览: 247
好的,以下是一个简单的学生学籍管理系统的 C 语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
struct student {
char name[50];
int id;
float gpa;
};
struct student students[MAX_STUDENTS];
int num_students = 0;
void add_student() {
struct student s;
printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter student ID: ");
scanf("%d", &s.id);
printf("Enter student GPA: ");
scanf("%f", &s.gpa);
students[num_students++] = s;
}
void print_student(struct student s) {
printf("Name: %s\n", s.name);
printf("ID: %d\n", s.id);
printf("GPA: %.2f\n", s.gpa);
}
void print_all_students() {
for (int i = 0; i < num_students; i++) {
printf("Student %d:\n", i+1);
print_student(students[i]);
}
}
void save_students() {
FILE *fp = fopen("students.txt", "w");
if (fp == NULL) {
printf("Error opening file!\n");
return;
}
for (int i = 0; i < num_students; i++) {
fprintf(fp, "%s %d %.2f\n", students[i].name, students[i].id, students[i].gpa);
}
fclose(fp);
}
void load_students() {
FILE *fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("Error opening file!\n");
return;
}
while (!feof(fp)) {
struct student s;
fscanf(fp, "%s %d %f\n", s.name, &s.id, &s.gpa);
students[num_students++] = s;
}
fclose(fp);
}
int main() {
int choice;
load_students();
do {
printf("\n1. Add student\n");
printf("2. Print all students\n");
printf("3. Save students to file\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
add_student();
break;
case 2:
print_all_students();
break;
case 3:
save_students();
break;
case 4:
break;
default:
printf("Invalid choice!\n");
}
} while (choice != 4);
return 0;
}
```
这个程序可以让用户添加学生信息,打印所有学生信息,将学生信息保存到文件中,并退出程序。
阅读全文