我正在尝试读取文件并打印跳线超出用户提供距离的记录,但搜索只返回文件中的第一行,就是这样,我知道逻辑中有错误但我不能把手指放在上面。
#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 Georgia 7.26
Christian Reif德国7.92
Christopher Tomlinson Great_Britain 8.06
答案 0 :(得分:2)
在search()
函数中:
if(distance > allPlayers[i].distance){
return i;
}
这将返回第一个跳线,其性能小于所提供的距离。
如果将其替换为:
if(allPlayers[i].distance > distance){
return i;
}
它将返回第一个跳线,其性能更大比提供的距离更多,这就是你想要的。
此外:
feof()
来阅读文件:Why is “while ( !feof (file) )” always wrong? main()
index
初始化为-1 myFileName
的大小,因为编译器可以解决这个问题