c - 程序不会打印 txt 文件中的所有行

标签 c printf scanf

写了这个程序,应该能够打印出txt文件中的所有行,但它只打印一行,现在已经看了1个小时了,我找不到错误,任何帮助都会得到帮助! :)

1 2011 年 7 月 16 日17.00 OB - FCN 2 - 0 6.965
1 2011 年 7 月 17 日14.00 FCM - SIF 1 - 2 5.370
1 2011 年 7 月 17 日16.00 ACH - HBK 3 - 0 2.227
1 2011 年 7 月 17 日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;
 }

最佳答案

您在每行输入末尾的出勤值导致了您的问题。您需要将其解析为 float 或用句点分隔的两个小数,而不仅仅是一个小数。假设出席人数永远不会达到一百万,它应该可以与下面的代码更改一起使用:

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);
}

关于c - 程序不会打印 txt 文件中的所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13552698/

相关文章:

c - 任何在保护模式下将字符串输入屏幕的尝试都会导致重新启动

c - 读取() : Unable to read file for/proc/$pid/status

c - 如何在C中打印内存地址

在 C 中复制多维数组

编译的枚举常量

使用 dlsym() 时进行转换

golang printf float 没有前导零

c - C 中带有 %s 参数的 printf() 和 fprintf() 调用的奇怪行为

你能告诉我为什么这个 C 程序没有按预期工作吗?

c - 使用 sscanf 读取字符串