请写一段C语言代码: 模拟KTV点歌系统。用户可按歌名查找某首歌曲或按歌手名查找其所有歌曲,点歌后显示所点歌曲歌词。管理员可添加和删除歌曲,每个歌曲的歌词用一个单独的文件存储
时间: 2024-02-11 18:05:33 浏览: 138
好的,以下是模拟KTV点歌系统的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SONGS 100
#define MAX_SONG_NAME_LENGTH 50
#define MAX_SINGER_NAME_LENGTH 30
#define MAX_LYRIC_LENGTH 1000
// 歌曲结构体
typedef struct {
char name[MAX_SONG_NAME_LENGTH];
char singer[MAX_SINGER_NAME_LENGTH];
char lyric_file[100];
} Song;
// 歌曲列表
Song songs[MAX_SONGS];
int num_songs = 0;
// 查找歌曲
void search_song() {
char keyword[MAX_SONG_NAME_LENGTH];
printf("请输入歌曲名或歌手名:");
scanf("%s", keyword);
int num_results = 0;
for (int i = 0; i < num_songs; i++) {
if (strstr(songs[i].name, keyword) != NULL ||
strstr(songs[i].singer, keyword) != NULL) {
printf("%d. %s - %s\n", num_results + 1, songs[i].singer, songs[i].name);
num_results++;
}
}
if (num_results == 0) {
printf("未找到匹配的歌曲或歌手\n");
} else {
int selected_song;
printf("请选择要点播的歌曲编号:");
scanf("%d", &selected_song);
if (selected_song < 1 || selected_song > num_results) {
printf("无效的歌曲编号\n");
} else {
char lyric[MAX_LYRIC_LENGTH];
FILE *lyric_file = fopen(songs[selected_song - 1].lyric_file, "r");
if (lyric_file == NULL) {
printf("歌词文件不存在\n");
} else {
fgets(lyric, MAX_LYRIC_LENGTH, lyric_file);
printf("正在播放 %s - %s,歌词如下:\n%s\n", songs[selected_song - 1].singer,
songs[selected_song - 1].name, lyric);
fclose(lyric_file);
}
}
}
}
// 添加歌曲
void add_song() {
if (num_songs == MAX_SONGS) {
printf("歌曲列表已满,无法添加新歌曲\n");
} else {
char name[MAX_SONG_NAME_LENGTH];
char singer[MAX_SINGER_NAME_LENGTH];
char lyric_file[100];
printf("请输入歌曲名:");
scanf("%s", name);
printf("请输入歌手名:");
scanf("%s", singer);
printf("请输入歌词文件名:");
scanf("%s", lyric_file);
strcpy(songs[num_songs].name, name);
strcpy(songs[num_songs].singer, singer);
strcpy(songs[num_songs].lyric_file, lyric_file);
num_songs++;
printf("已成功添加新歌曲:%s - %s\n", singer, name);
}
}
// 删除歌曲
void delete_song() {
char name[MAX_SONG_NAME_LENGTH];
printf("请输入要删除的歌曲名:");
scanf("%s", name);
int song_index = -1;
for (int i = 0; i < num_songs; i++) {
if (strcmp(songs[i].name, name) == 0) {
song_index = i;
break;
}
}
if (song_index == -1) {
printf("歌曲不存在\n");
} else {
for (int i = song_index; i < num_songs - 1; i++) {
songs[i] = songs[i + 1];
}
num_songs--;
printf("已成功删除歌曲:%s\n", name);
}
}
int main() {
while (1) {
int choice;
printf("\n请选择您的身份:\n1. 用户\n2. 管理员\n0. 退出\n");
scanf("%d", &choice);
if (choice == 0) {
printf("感谢使用KTV点歌系统,下次再见!\n");
break;
} else if (choice == 1) {
search_song();
} else if (choice == 2) {
int admin_choice;
printf("\n管理员,请选择您的操作:\n1. 添加歌曲\n2. 删除歌曲\n0. 返回上一级\n");
scanf("%d", &admin_choice);
if (admin_choice == 0) {
continue;
} else if (admin_choice == 1) {
add_song();
} else if (admin_choice == 2) {
delete_song();
} else {
printf("无效的选项\n");
}
} else {
printf("无效的选项\n");
}
}
return 0;
}
```
这段代码实现了一个简单的KTV点歌系统。用户可以按歌名或歌手名查找歌曲,点歌后会显示该歌曲的歌词。管理员可以添加和删除歌曲,每个歌曲的歌词使用一个单独的文件进行存储。
阅读全文