无休止的 while 循环和 fscanf 没有将数据分配给结构

Endless while loop and fscanf not assigning data to struct

作为一项学校作业,我的任务是阅读足球比赛列表,语法如下

weekday date time hometeam - outteam hometeam goals - outteam goals #spectators thsi 的一个例子可以是

FRI 18/07 18.30 FCN - FCV 3 - 2 3.349

这将使以下条目进入我的结构

struct match_data
{
    char match_day[4];
    int match_date_day;
    int match_date_month;
    char match_time[6];
    char match_home_team[4];
    char match_away_team[4];
    int match_home_goals;
    int match_away_goals;
    int match_spectators;
};

match_day:星期五

match_date_day: 18

match_date_month: 07

match_time: 18.30

match_home_team: FCN

match_away_team:燃料电池汽车

match_home_goals: 3

match_away_goals: 2

match_spectators: 3.349

所以当我尝试读取文件时出现问题

我的 while 循环似乎永远持续下去,当我 运行 代码按原样(用 printf 测试是否已分配数据)

int game_loader()
{
    int i = 0;
    FILE *file_pointer;

    file_pointer = fopen("superliga-2014-2015", "r");

    if(!file_pointer == NULL)
    {
        printf("Error opening file");
        return -1;
    }

    struct match_data match[200];
    while(!feof(file_pointer))
    {
        fscanf(file_pointer, "%[^ ][^0-9]%d/%d %[^ ][^A-Z]%[^ ] - %[^ ][^0-9]%d - %d[^ ]%d[^\n]\n",
        match[i].match_day,         &match[i].match_date_day,   &match[i].match_date_month,
        match[i].match_time,        match[i].match_home_team,   match[i].match_away_team, &match[i].match_home_goals,   &match[i].match_away_goals, &match[i].match_spectators);

        printf("day %d: %s\n", i, match[i].match_day);
        i++;
    }

    printf("match day is: %s\n"
        "match date is: %d/%d"
        "match time is: %s"
        "match is between %s - %s"
        "Score was: %d - %d"
        "the amount of spectators was: %d",
        match[1].match_day,         match[1].match_date_day,    match[1].match_date_month,
        match[1].match_time,        match[1].match_home_team,   match[1].match_away_team,
        match[1].match_home_goals,  match[1].match_away_goals,       match[1].match_spectators);

    return 0;
}

不仅循环永远不会关闭,而且 fscanf 也永远不会将数据分配给变量

我认为这是因为当我尝试从 match_day 移动到 match_date_day 时我错误地格式化了 fscanf 我尝试使用 [^0-9] 跳过日期和日期之间的空格日期

您应该检查调用的函数是否存在潜在故障。 特别是 功能容易 失败*scanf()。这是你应该养成的习惯。

您可能正在查看匹配失败,即输入与您的格式字符串不匹配,这使得 *scanf() return 提前 而没有推进文件中的位置.

所以你只是不断尝试(并失败)一遍又一遍地读取相同的数据。

此外,如果 *scanf() 失败,match_day*printf() 可能会调用未定义的行为(打印未初始化的值)。 ;-)


至于为什么你的*scanf()失败了...我很确定你不能multiple [...] in one 转换说明符。