【问题标题】:Sorting Greed High Scores(File I/O)排序贪婪高分(文件 I/O)
【发布时间】:2015-05-24 18:21:05
【问题描述】:

我正在用 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);
   }
}

【问题讨论】:

  • 不需要这行:'else if (fhigh_score) {' 因为前面的 'if' 已经处理了打开文件读取的任何错误
  • 注意到了。但是我怎样才能按谁的得分最高对它们进行排序呢?

标签: c sorting file-io


【解决方案1】:

您需要一个数据结构来存储玩家及其得分。例如:

struct Player {
    const char* name;
    int score;
};

然后您可以创建一个此类结构的数组,将文件中的所有播放器数据放在那里,然后应用 qsort() 对其进行排序。您还需要一个比较函数来按分数对玩家进行排序以提供给 qsort。

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 1970-01-01
    • 2023-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 2017-02-27
    • 1970-01-01
    相关资源
    最近更新 更多