[英]Sorting Greed High Scores(File I/O)
我正在用C語言實現Greed(greedjs.com)的過程中。如何將這些數據從最高到最低排序,以及如何追加僅符合前十名的得分?
這是它的樣子。
到目前為止,這是我的代碼:
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。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.