帮我用代码写一个学生成绩管理系统
时间: 2023-03-26 09:00:22 浏览: 85
你好,我可以为您提供一个学生成绩管理系统的代码示例。以下是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENTS 100
typedef struct {
char name[20];
int id;
int score;
} Student;
int num_students = ;
Student students[MAX_STUDENTS];
void add_student() {
if (num_students >= MAX_STUDENTS) {
printf("Error: too many students\n");
return;
}
Student s;
printf("Enter student name: ");
scanf("%s", s.name);
printf("Enter student ID: ");
scanf("%d", &s.id);
printf("Enter student score: ");
scanf("%d", &s.score);
students[num_students++] = s;
}
void print_students() {
printf("Name\tID\tScore\n");
for (int i = ; i < num_students; i++) {
printf("%s\t%d\t%d\n", students[i].name, students[i].id, students[i].score);
}
}
void save_students() {
FILE *fp = fopen("students.txt", "w");
if (fp == NULL) {
printf("Error: could not open file\n");
return;
}
for (int i = ; i < num_students; i++) {
fprintf(fp, "%s %d %d\n", students[i].name, students[i].id, students[i].score);
}
fclose(fp);
}
void load_students() {
FILE *fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("Error: could not open file\n");
return;
}
while (1) {
Student s;
int n = fscanf(fp, "%s %d %d\n", s.name, &s.id, &s.score);
if (n != 3) break;
students[num_students++] = s;
}
fclose(fp);
}
int main() {
load_students();
while (1) {
printf("Enter command (add, print, save, quit): ");
char cmd[10];
scanf("%s", cmd);
if (strcmp(cmd, "add") == ) {
add_student();
} else if (strcmp(cmd, "print") == ) {
print_students();
} else if (strcmp(cmd, "save") == ) {
save_students();
} else if (strcmp(cmd, "quit") == ) {
break;
} else {
printf("Error: invalid command\n");
}
}
return ;
}
希望这个代码示例能够帮到您!
阅读全文