簡體   English   中英

無休止的 while 循環和 fscanf 未將數據分配給結構

[英]Endless while loop and fscanf not assigning data to struct

作為一項學校作業,我的任務是閱讀足球比賽列表,語法如下

weekday date time hometeam - outteam hometeam goals - outteam goals #spectators一個例子可能是

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_date_day: 18

match_date_month: 07

比賽時間:18.30

match_home_team:FCN

match_away_team:FCV

match_home_goals: 3

match_away_goals: 2

比賽觀眾: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 永遠不會將數據分配給變量

即時通訊思想,那是因為我當我試圖從移動不正當格式化的fscanf match_daymatch_date_day我嘗試使用[^ 0-9]跳過空格在白天和日期之間

您應該檢查您調用的函數是否存在潛在故障。 特別是*scanf()一樣容易失敗的功能。 這是你應該養成的習慣。

您可能正在查看匹配失敗,即輸入與您的格式字符串不匹配,這使得*scanf()提前返回而不推進文件中的位置

所以你只是不斷嘗試(但失敗)一遍又一遍地讀取相同的數據。

此外,如果*scanf()失敗, match_day*printf()可能會調用未定義的行為(打印未初始化的值)。 ;-)


至於為什么你的*scanf()失敗了......我很確定你不能一個轉換說明符中有多個[...]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM