给定某学生学号修改该学生班级信息的代码
时间: 2023-04-04 09:01:11 浏览: 153
以下是修改学生班级信息的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STUDENT_NUM 100
#define MAX_CLASS_NAME_LEN 20
typedef struct {
char id[10];
char name[20];
char class_name[MAX_CLASS_NAME_LEN];
} Student;
int main() {
Student students[MAX_STUDENT_NUM];
int student_num = ;
char target_id[10];
char new_class_name[MAX_CLASS_NAME_LEN];
// 读取学生信息
FILE *fp = fopen("students.txt", "r");
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
while (fscanf(fp, "%s %s %s", students[student_num].id, students[student_num].name, students[student_num].class_name) != EOF) {
student_num++;
}
fclose(fp);
// 输入要修改的学生学号和新班级名称
printf("请输入要修改的学生学号:");
scanf("%s", target_id);
printf("请输入新的班级名称:");
scanf("%s", new_class_name);
// 查找要修改的学生并修改班级名称
int found = ;
for (int i = ; i < student_num; i++) {
if (strcmp(students[i].id, target_id) == ) {
strcpy(students[i].class_name, new_class_name);
found = 1;
break;
}
}
// 输出修改结果
if (found) {
fp = fopen("students.txt", "w");
if (fp == NULL) {
printf("无法打开文件\n");
return 1;
}
for (int i = ; i < student_num; i++) {
fprintf(fp, "%s %s %s\n", students[i].id, students[i].name, students[i].class_name);
}
fclose(fp);
printf("修改成功!\n");
} else {
printf("未找到该学生!\n");
}
return ;
}
```
阅读全文