c语言运动会积分系统存储到txt文件中修改的代码模块
时间: 2023-12-22 13:05:14 浏览: 86
以下是一个简单的 C 代码模块,可以将运动会积分系统的数据存储到 txt 文件中,并且可以修改已有的数据:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_TEAMS 100
#define MAX_NAME_LENGTH 20
struct Team {
char name[MAX_NAME_LENGTH];
int score;
};
struct Team teams[MAX_TEAMS];
int num_teams = 0;
void add_team(char *name) {
if (num_teams >= MAX_TEAMS) {
printf("Too many teams!\n");
return;
}
strcpy(teams[num_teams].name, name);
teams[num_teams].score = 0;
num_teams++;
}
void print_teams() {
printf("Team\tScore\n");
for (int i = 0; i < num_teams; i++) {
printf("%s\t%d\n", teams[i].name, teams[i].score);
}
}
int find_team(char *name) {
for (int i = 0; i < num_teams; i++) {
if (strcmp(teams[i].name, name) == 0) {
return i;
}
}
return -1;
}
void update_score(char *name, int score) {
int index = find_team(name);
if (index == -1) {
printf("Team %s not found!\n", name);
return;
}
teams[index].score += score;
}
void save_data(char *filename) {
FILE *fp = fopen(filename, "w");
if (fp == NULL) {
printf("Error opening file %s!\n", filename);
return;
}
for (int i = 0; i < num_teams; i++) {
fprintf(fp, "%s %d\n", teams[i].name, teams[i].score);
}
fclose(fp);
}
void load_data(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error opening file %s!\n", filename);
return;
}
char name[MAX_NAME_LENGTH];
int score;
while (fscanf(fp, "%s %d", name, &score) == 2) {
add_team(name);
update_score(name, score);
}
fclose(fp);
}
int main() {
load_data("scores.txt");
char command[100];
char name[MAX_NAME_LENGTH];
int score;
while (1) {
printf("> ");
scanf("%s", command);
if (strcmp(command, "add") == 0) {
scanf("%s", name);
add_team(name);
} else if (strcmp(command, "update") == 0) {
scanf("%s %d", name, &score);
update_score(name, score);
} else if (strcmp(command, "print") == 0) {
print_teams();
} else if (strcmp(command, "save") == 0) {
scanf("%s", name);
save_data(name);
} else if (strcmp(command, "quit") == 0) {
break;
} else {
printf("Invalid command!\n");
}
}
return 0;
}
```
这个代码模块提供了以下几个功能:
1. 添加一个新的队伍 `add [队伍名称]`。
2. 更新一个队伍的得分 `update [队伍名称] [分数]`。
3. 打印所有队伍的得分 `print`。
4. 将数据保存到指定的 txt 文件中 `save [文件名]`。
5. 退出程序 `quit`。
你可以根据需要对这个代码模块进行修改和扩展。
阅读全文