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

标签 c search sequential

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

    #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

克里斯蒂安·赖夫德国 7.92

克里斯托弗·汤姆林森 Great_Britain 8.06

最佳答案

在您的 search() 函数中:

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

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

如果将其替换为:

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

它将返回第一个表现大于超过所提供距离的跳投者,这正是您想要的。

另外:

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

关于c - 搜索仅返回结构 C 中的第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916222/

相关文章:

linux - 在多个文件中搜索日期/时间

Rails 中的 MySQL 全文搜索?

python-3.x - 构建顺序模型时如何修复 'the added layer must be an instance of class layer'?

FFMPEG - 如何将帧提取为图像,同时删除连续重复的帧

python - 如何顺序运行多个 python 脚本?

c - 段错误(核心已转储)- C 参数

c - 指针数组的段错误

c - 使用系统调用读写

search - 在 IntelliJ 全局搜索中从搜索结果中排除评论?

objective-c - C作为主要类(class);或没有ObjC的 cocoa 应用