我正在尝试读取文件并打印跳线超出用户提供的距离的记录,但搜索仅返回文件中的第一行,仅此而已,我知道逻辑中有问题但我不能 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;
}
它将返回第一个表现大于超过所提供距离的跳投者,这正是您想要的。
另外:
- 不要循环遍历
feof()
来读取文件:Why is “while ( !feof (file) )” always wrong? - 当您尚未加载数据时,您正在打印“数据已成功加载” - 您刚刚打开了文件
- 您不需要
main()
的参数 - 在下一行中分配
index
时,无需将其初始化为 -1 - 您无需指定
myFileName
的大小,因为编译器可以计算出
关于c - 搜索仅返回结构 C 中的第一个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41916222/