0

txtファイルからすべての行を印刷できるはずのこのプログラムを作成しましたが、印刷されるのは1つだけで、1時間見ていて間違いを見つけることができません。:)

1 16.07.2011 kl。17.00 OB - FCN 2 - 0 6.965
1 17.07.2011 kl. 14.00 FCM - SIF 1 - 2 5.370
1 17.07.2011 kl. 16.00 ACH - HBK 3 - 0 2.227
1 17.07.2011 kl. 16.00 SDR - FCK 0 - 2 4.992
最初の 4 行。

#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LGT 200
#define NAME_MAX 200
#define TEAM_MAX 200

struct team{
char name[NAME_MAX];
int five_or_more_goals;
};
typedef struct team team;

void read_data_1(const char *file_name, team teams[]){
FILE *ifp;
char team1[NAME_MAX];
char team2[NAME_MAX];
int goal1, goal2;
int dag, month, year;
double clock;
int attendance;
int round;
team local_match;

ifp = fopen(file_name, "r");

while (fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %d\n", &round, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10){
    printf("runde %d den %d %d %d klokken %.2lf, mellem %s og %s endte %d - %d %d så kampen\n", round, dag, month, year, clock, team1, team2, goal1, goal2, attendance);
    }

fclose(ifp);

   }

  int main(void) {
  team all_matches_teams[TEAM_MAX];
  read_data_1("superliga-2011-2012", all_matches_teams);

 return 0;
 }
4

2 に答える 2

1

入力の各行の最後にある出席率が問題を引き起こしています。1 つの小数だけでなく、浮動小数またはピリオドで区切られた 2 つの小数として解析する必要があります。出席者が 100 万人に達しないと仮定すると、以下のコード変更で動作するはずです。

int valuesRead;
int attendance;
int attend1, attend2;
[...]
while ((valuesRead = fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %d.%d\n", &round, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attend1, &attend2)) >= 10){
    if (valuesRead == 11)
        attendance = attend1 * 1000 + attend2;
    else
        attendance = attend1;
    printf("runde %d den %d %d %d klokken %.2lf, mellem %s og %s endte %d - %d %d så kampen\n", round, dag, month, year, clock, team1, team2, goal1, goal2, attendance);
}
于 2012-11-25T16:56:16.293 に答える
0

入力してくれてありがとう、出席変数を double に変更するだけで問題なく動作するようになりました。コードをもう一度示します。よりスマートに書くためのヒントがあれば、教えてください! :)

#include <stdio.h>
#include <stdlib.h>
#define MAX_LINE_LGT 200
#define NAME_MAX 200
#define TEAM_MAX 200

struct team{
char name[NAME_MAX];
int five_or_more_goals;
};
typedef struct team team;

void read_data_1(const char *file_name, team teams[]){
FILE *ifp;
char team1[NAME_MAX];
char team2[NAME_MAX];
int goal1, goal2;
int dag, month, year;
double clock;
double attendance;
int round;
team local_match;

ifp = fopen(file_name, "r");

while (fscanf(ifp, "%d %d.%d.%d kl. %lf %4s - %4s %d - %d %lf\n", &round, &dag, &month, &year, &clock, team1, team2, &goal1, &goal2, &attendance) == 10){
    printf("runde %d den %d %d %d klokken %.2lf, mellem %s og %s endte %d - %d %.3lf så kampen\n", round, dag, month, year, clock, team1, team2, goal1, goal2, attendance);
    }

fclose(ifp);

    }

  int main(void) {
  team all_matches_teams[TEAM_MAX];
  read_data_1("superliga-2011-2012", all_matches_teams);

  return 0;
  }
于 2012-11-25T17:13:01.887 に答える