【问题标题】:Sorting Words and Numbers from a file in CC语言对文件中的单词和数字进行排序
【发布时间】:2023-03-08 00:48:01
【问题描述】:

我的任务是编写一个接受字符串引用和整数引用参数的函数。该函数必须扫描一个.txt文件,并将参考参数设置为得分最高的玩家的名字和对应的得分。 这是写在我必须参考的scores.txt文件中:

Ronaldo
10400
Didier
9800
Pele
12300
kaka
8400
Cristiano
8000

我目前写了这么多编码,但是我不知道我应该如何将名称与分数匹配,因为它们必须没有特定的顺序。在我的编码中,我将数字从大到小排序,但我不确定是否需要这样做。

FILE *input;
char name[name_len];
double score[score_len];
int a;
int b;
double placeholder;

input = fopen("scores.txt", "r");

if (input == NULL)
{
    printf("\n Cannot open scores.txt for input\n");
}
for (a =0; a < 5; ++a)
fscanf(input, "%s%lf", name, score);

for (a = 0; a < 5; ++a)                                     /* Repeats the step until three numbers are sorted*/
{
    for (b = a + 1; b < 5; ++b)                             /* Repeats until the last two numbers are sorted*/
    {
        if (score[a] < score[b])                                /* Sorts the 3 numbers using a placeholder to exchange the numbers in the array*/
        {
            placeholder = score[a];
            score[a] = score[b];
            score[b] = placeholder;
        }

    }
}


fclose(input);
return 0;

非常感谢有关解决方案或我如何前进的任何帮助。

【问题讨论】:

  • 如果这些是完整的要求,你不需要排序。只需在读取输入文件时跟踪迄今为止看到的最大分数。如果您发现更大的乐谱,请使用相应的名称存储它。
  • 另外,这被标记为 C 但你提到了引用。您的意思是标记为 C++ 吗?
  • 答案是“贝利”,得分为“12300”。代码已经在一个fscanf中读取了名字和对应的分数。您需要做的就是将分数与迄今为止看到的最佳分数进行比较。如果新分数更好,则将strcpyname换成另一个字符串,并更新最佳分数。

标签: c arrays string file sorting


【解决方案1】:

您可以只读取其中的数字和名称,如果分数和名称较大,则替换分数的值。

char name[name_len];
double score[score_len];
char highScoreName[name_len];
double highScore = 0;
...
for (int a = 0; a < 5; ++a) 
   {
   fscanf(input, "%s %lf", name, score[a]);
   if (highScore < score[a]) 
   {
      highScore = score[a];
      strcpy(highScoreName, name);
   }
}

【讨论】:

  • 我已经更新了我的代码以反映你告诉我要做的更改:input = fopen("scores.txt", "r"); if (input == NULL) { printf("\n Cannot open scores.txt for input\n"); } for (a = 0; a &lt; 5; ++a) { fscanf(input, "%s%lf", name, score); if (highscore &lt; score[a]) { highscore = score[a]; strcpy(highscorename, name); } } printf(" The highscore is %s with %f points.", highscorename, score); printf("\n\n"); fclose(input); 但是现在 Visual Studio 告诉我 fopen、fscanf 和 strncpy 是不安全的。你知道为什么会这样吗?
  • 我也得到错误'printf':格式字符串'%f'需要'double'类型的参数,但是可变参数2有'double*'类型为什么我也会得到这个错误??
  • unsafe 警告可能是因为 Visual Studio 看到 input 可以是 NULL 并且无法打开,但您实际上并没有对它做任何事情,除了打印一条消息。在尝试对可能无效的文件描述符进行操作之前,您应该返回退出程序的 1。至于printf,警告是不言自明的......分数的类型是double *,你想打印highScore
  • 我应该把“return 1”放在哪里?我把它放在我之前有“return 0”的编码的末尾,但我仍然得到错误。谢谢
  • if (input == NULL){} 语句中。这样,如果文件无法打开,程序就会退出,并且您不会尝试在无效的文件指针上调用 fscanf 等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 2016-02-08
相关资源
最近更新 更多