搜索仅返回结构 C 中的第一个结果

Search returning only the first result in structure C

我正在尝试读取一个文件并打印跳线超出用户提供的距离的记录,但只搜索 returns 文件中的第一行,仅此而已,我知道那里逻辑上有问题,但我不能指责它。

    #include<stdio.h>
    #include<string.h>

typedef struct {
    char fname[30];
    char lname[30];
    char nationality [30];
    double distance;
}Player;

void print(Player p) {
    printf("%s %s %s %f \n", p.fname, p.lname, p.nationality, p.distance);
}
int search(double distance, Player allPlayers[], int max){
    int i=0;
    for(i=0; i<max; i++){
        if(distance > allPlayers[i].distance){
            return i;
        }
        return -1;
    }
}

void load (char filename[10], Player players[]){

    char tempfName [30];
    char templName [30];
    char tempNationality [30];
    double tmpdistance;
    FILE * input=fopen(filename,"r+");
    if(input==NULL)
        printf("Error found in opening the file\n");
    else {
        printf("The data are loaded successfully.\n");
        int counter = 0;
        while(!feof(input)){

            strcpy(tempfName," ");
            fscanf(input, "%s %s %s %f",tempfName, templName, tempNationality, &tmpdistance);
            if(strcmp(tempfName, " ") !=0){
                strcpy(players[counter].fname, tempfName);
                strcpy(players[counter].lname, templName);
                strcpy(players[counter].nationality, tempNationality);
                players[counter].distance = tmpdistance;
                counter++;
            }
        }
            fclose(input);
    }
}
int main (int argc, char *argv[]){

    Player players2[40];
    char myFileName[10] ="jump.txt";

    load(myFileName, players2);

    double tmpdistance;
    printf("Please enter the distance threshold: "); 
    scanf("%lf", &tmpdistance);
    printf("The jumpers exceeded 8.10 m are: \n"); 
    int index = -1;
    index = search(tmpdistance,players2,40);

    if(index!=-1)
        print(players2[index]);

    else
        printf("NOT Found! \n");

    return 0;
}

我正在尝试读取的文件中的一些示例数据:

Arsen Sargsyan 亚美尼亚 7.62

格鲁吉亚 Boleslav Skhirtladze 7.26

Christian Reif 德国 7.92

克里斯托弗汤姆林森 Great_Britain 8.06

在您的 search() 函数中:

if(distance > allPlayers[i].distance){
    return i;
}

这将是第一个 return 表现 小于 所提供距离的跳投者。

如果将其替换为:

if(allPlayers[i].distance > distance){
    return i;
}

它将return第一个表现大于的跳投者,这正是您想要的。

还有:

  1. 不要循环 feof() 来读取文件:Why is “while ( !feof (file) )” always wrong?
  2. 您尚未加载数据时正在打印 "The data are loaded successfully" - 您刚刚打开文件
  3. 您不需要 main()
  4. 的参数
  5. 您不需要将 index 初始化为 -1,因为您在下一行中分配它
  6. 您不需要指定 myFileName 的大小,因为编译器可以计算出来