我会假设您只关心哪一轮的目标最多,并且您不需要像@Ben 建议的那样将文本文件存储在内存中。
如果是这种情况,您可以执行以下操作:
int i, maxGoals = 0, roundWithMostGoals = 0;
for (i = 0; fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &runde, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10; ++i)
{
if (maxGoals < goal1 + goal2)
{
roundWithMostGoals = runde;
maxGoals = goal1 + goal2;
}
}
// Edit:
printf("The largest number of goals was %d, scored in round %d", maxGoals, roundWithMostGoals);
这段代码确实有问题。如果有两轮进球数最多,则只打印第一轮。
为了避免这种情况,我们需要循环两次,这并不理想,我建议使用其他建议的方法之一,将所有这些数据加载到内存中。
但是,这是一个修改后的解决方案,即使我认为它不是最佳的:
int i, maxGoals = 0, roundWithMostGoals = 0;
// Find the maximum number of goals that was scored in any one round.
for (i = 0; fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &runde, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10; ++i)
{
if (maxGoals < goal1 + goal2)
{
maxGoals = goal1 + goal2;
}
}
printf("The largest number of goals scored was %d.\n", maxGoals);
printf("The largest number of goals was scored in\n");
// TODO: Reposition the file stream back to the beginning or close it and then reopen it again.
// XXX Code Here XXX
// Loop through again getting all the rounds with the maximum number of goals.
for (i = 0; fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &runde, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10; ++i)
{
if (maxGoals == goal1 + goal2)
{
printf("\tRound %d\n", runde);
}
}
但这现在循环了两次,绝对不是解决问题的最佳方法。