我正在用 C 实现 Greed(greedjs.com)。我如何将这些数据从最高到最低排序,以及如何附加仅符合前十名玩家资格的分数?
Here's它看起来像什么。
这是我到目前为止的代码:
void high_scores() {
int c;
char player_name[256];
FILE * fhigh_score;
fhigh_score = fopen("HIGH SCORES.txt", "a");
if (fhigh_score == NULL) {
printf("Error");
exit(1);
}
printf("Your Name:\t");
fgets(player_name, 256, stdin);
player_name[strlen(player_name) - 1] = 0;
fprintf(fhigh_score, "\t%s\t%d\n", player_name, SCORE);
fclose(fhigh_score);
fhigh_score = fopen("HIGH SCORES.txt", "r");
if (fhigh_score == NULL) {
printf("Error");
exit(1);
}
else if (fhigh_score) {
while ((c = getc(fhigh_score)) != EOF) //print file to terminal
putchar(c);
fclose(fhigh_score);
}
}
最佳答案
您需要的是一个数据结构来存储玩家及其得分。例如:
struct Player {
const char* name;
int score;
};
然后您可以创建一个此类结构的数组,将文件中的所有玩家数据放在那里,然后应用qsort()
对其进行排序。您还需要一个比较函数来按得分对玩家进行排序,以提供给 qsort。
关于c - 排序贪婪高分(文件 I/O),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30426810/