所以我想做的是找出如何按最小数字对文件进行排序。这些数字在一个结构中。该程序有点像记分牌。您可以添加姓名并包括分数(在本例中是关于运行者和所用时间)。
添加姓名后,程序会按最佳时间将分数和运行者排序到一个文件中。
我不知道如何:
- 按最低/最高排序。
- 在排序后保持运行者的名字和他们的分数完整。
代码:
#include <stdio.h>
#include <string.h>
struct kilpailijat //The structure im using
{
char nimi[43+1];
float aika;
};
int main() {
int i, maara;
struct kilpailijat henkilo[50];
FILE *tulos;
size_t ln;
while (1 != 0) {
printf("Montako kilpailijaa haluat lisätä? (max 50): "); //How many runners
scanf_s("%d", &maara); // User input of how many runners
while (getchar() != '\n');
if (maara > 50) { //Checks that the ammount of runners is no more then 50
printf("Yritit lisätä liian monta kilpailijaa.\n");
} else if (maara < 0) { //And no less then 0
printf("Mielenkiintoista. Jos yrittäisit uudelleen.\n");
} else if (maara == 0) { // Zero Quits the program
return 0;
} else {
break;
}
}
for (i = 0; i < maara; i++){ // Start loop to add runners and their score.
printf("\nAnna kilpailijan nimi: ");
fgets(&henkilo[i].nimi[0], 43, stdin); //Add name of runner
ln = strlen(henkilo[i].nimi) - 1; //Remove newline off of fgets()
if (henkilo[i].nimi[ln] == '\n'){
henkilo[i].nimi[ln] = '\0';
}
printf("Kilpailijan aika: "); //Add score
scanf_s("%f", &henkilo[i].aika);
while (getchar() != '\n');
}
if ((tulos = fopen("tulos.txt", "w")) == NULL){ // Check if file opens
printf("Tiedoston avauksessa tapahtui virhe.\n");
}
for (i = 0; i < maara; i++){ //Writes Name and Score to file.
fprintf(tulos, "%s\t%.1f\n", henkilo[i].nimi, henkilo[i].aika);
}
fclose(tulos);
}
最佳答案
使用qsort并实现自定义比较方法。
int compare (const void * a, const void * b)
{
float f1 = ((struct kilpailijat *)a)->aika;
float f2 = ((struct kilpailijat *)b)->aika;
int result = 0;
if (f1 < f2)
{
result = -1;
}
else if (f1 > f2)
{
result = 1;
}
return result;
}
然后:
qsort (henkilo, maara, sizeof(kilpailijat), compare);
更新:
女士们,先生们,我很自豪地向大家展示 working example .
它使用了三种我不是特别熟悉的语言……芬兰语、英语和 C!
关于C:如何按最小数字对文件进行排序(使用结构)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14638822/