【发布时间】: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