游戏防沉迷
c语言实现:输入n行数据,每行包含人名 和 游戏名,按照人名出现的顺序,输出人名和他玩过的游戏;
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_PEOPLE 100 #define MAX_GAMES 50 #define MAX_NAME_LEN 50 // 结构体存储人名和对应的游戏列表 typedef struct { char name[MAX_NAME_LEN]; char games[MAX_GAMES][MAX_NAME_LEN]; int game_count; } Person; Person people[MAX_PEOPLE]; int person_count = 0; // 查找人名在数组中的位置,如果不存在则添加 int find_or_add_person(const char *name) { for (int i = 0; i < person_count; i++) { if (strcmp(people[i].name, name) == 0) { return i; // 找到,返回索引 } } // 没找到,添加新人 if (person_count < MAX_PEOPLE) { strcpy(people[person_count].name, name); people[person_count].game_count = 0; return person_count++; } return -1; // 数组已满 } // 为指定的人添加游戏(如果该游戏不存在) void add_game(int person_index, const char *game) { Person *p = &people[person_index]; // 检查游戏是否已经存在 for (int i = 0; i < p->game_count; i++) { if (strcmp(p->games[i], game) == 0) { return; // 游戏已存在,不重复添加 } } // 添加新游戏 if (p->game_count < MAX_GAMES) { strcpy(p->games[p->game_count], game); p->game_count++; } } int main() { int n; char name[MAX_NAME_LEN]; char game[MAX_NAME_LEN]; printf("请输入数据行数: "); scanf("%d", &n); getchar(); // 消耗换行符 printf("请输入%d行数据(格式:人名 游戏名):\n", n); // 读取输入数据 for (int i = 0; i < n; i++) { scanf("%s %s", name, game); getchar(); // 消耗换行符 int index = find_or_add_person(name); if (index != -1) { add_game(index, game); } } // 按照人名出现的顺序输出结果 printf("\n输出结果:\n"); for (int i = 0; i < person_count; i++) { printf("%s: ", people[i].name); for (int j = 0; j < people[i].game_count; j++) { printf("%s", people[i].games[j]); if (j < people[i].game_count - 1) { printf(", "); } } printf("\n"); } return 0; }