用C语言编写函数实现美食评分排序(从文本文件中读入数据)
时间: 2024-01-28 20:04:08 浏览: 67
好的,以下是用 C 语言编写函数实现美食评分排序(从文本文件中读入数据)的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct food {
char name[20];
float score;
};
int cmp(const void *a, const void *b) {
struct food *fa = (struct food *)a;
struct food *fb = (struct food *)b;
return (fa->score > fb->score) ? -1 : 1;
}
void sort_foods_by_score(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("Error: Failed to open file %s\n", filename);
return;
}
int max_foods = 100;
struct food *foods = (struct food *)malloc(max_foods * sizeof(struct food));
int num_foods = 0;
char line[50];
while (fgets(line, 50, fp) != NULL) {
char *name = strtok(line, ",");
char *score_str = strtok(NULL, ",");
float score = atof(score_str);
struct food f;
strcpy(f.name, name);
f.score = score;
if (num_foods == max_foods) {
max_foods *= 2;
foods = (struct food *)realloc(foods, max_foods * sizeof(struct food));
}
foods[num_foods++] = f;
}
fclose(fp);
qsort(foods, num_foods, sizeof(struct food), cmp);
printf("Sorted foods by score:\n");
for (int i = 0; i < num_foods; i++) {
printf("%s: %.1f\n", foods[i].name, foods[i].score);
}
free(foods);
}
int main() {
sort_foods_by_score("foods.txt");
return 0;
}
```
其中,`struct food` 表示一个美食,包含两个成员:`name` 表示美食名称,`score` 表示美食评分。`cmp` 函数是一个比较函数,用于 `qsort` 函数对美食评分进行排序。`sort_foods_by_score` 函数用于从指定的文本文件中读入美食数据,进行排序并输出结果。在实现中,我们使用了动态内存分配,以便在读入的美食数量不断增加时,能够自动扩展内存空间。
请注意,这只是一个简单的示例代码,实际应用中还需要考虑各种边界情况和异常处理,比如文件不存在、文件格式错误等。
阅读全文