2016-01-20 38 views
1

我正在編寫一個程序,它將逐行讀取文件中的信息,然後將信息加載到雙向鏈接列表中。該信息被加載的結構,稱爲tvshow:將信息從文件加載到列表中c

typedef struct tvshow{ 
    char name[20]; 
    int epNumber; 
    int year; 
    float duration; 
    char country[3]; 
    char genre[20]; 
}tvshow; 

typedef struct node{ 
    tvshow inf; 
    struct node *next; 
    struct node *prev; 
}node; 

void insert(node **, tvshow); 
void print(node *); 
FILE *safe_open(char *, char *); 
void load(node **, FILE *); 

int main(){ 
    node *head; 
    head=NULL; 

    FILE *in=safe_open("tvshows.txt", "r"); 

    load(&head, in); 
    print(head); 

    fclose(in); 

    return 0; 
    } 

void insert(node **head, tvshow data){ 
    node *new=malloc(sizeof(node)); 
    new->inf=data; 
    new->next=NULL; 

    if (*head==NULL){ 
     *head=new; 
     new->prev=NULL; 
    }else{ 
     node *temp=*head; 
     while (temp->next!=NULL){ 
     temp=temp->next; 
    } 
    temp->next=new; 
    new->prev=temp; 
    } 
} 

void print(node *head){ 
    while (head!=NULL){ 
     printf("%s %d %d %f %s %s\n", head->inf.name,head->inf.epNumber,head->inf.year, head->inf.duration,head->inf.country, head->inf.genre); 
     head=head->next; 
    } 
} 

FILE *safe_open(char *name, char *mode){ 
    FILE *fp=fopen(name, mode); 

    if (fp==NULL){ 
     printf("failed to open"); 
     exit(1); 
    } 

    return fp; 
} 

void load(node **head, FILE *fp){ 
    tvshow temp; 

    while (fscanf(fp, "%s %d %d %f %s %s", temp.name, &temp.epNumber,&temp.year, &temp.duration, temp.country, temp.genre)!=EOF){ 
     insert(head, temp); 
    } 
} 

這裏是從.txt文件的示例行: TheSopranos 86 1999 55 USA Drama

是什麼在困擾我的是,當我運行該程序,它打印以下:

TheSopranos 86 1999 55 USADrama Drama 

爲什麼USADrama?它出了什麼問題?

+0

嘗試改變焦炭的國家[3]到char國家[4]爲 '\ 0' – novice

+0

@novice試過了,還是一樣...做你有其他想法嗎? – sstefan

+0

@novice其實它的工作,我的壞...謝謝 – sstefan

回答

1

變化char country[3]char country[4]爲 '\ 0' 空字符

+0

確實如此,但幾乎沒有三個字母的國家。另外,電視節目「名稱[20]」和「類型[20]」可能會耗盡。考慮爲名稱分配內存,並存儲一個指針。考慮有一個引用流派的列表,這將解決任何用戶的拼寫錯誤問題。 –

+0

我認爲這是他存檔的方式。也許他將所有國家名稱存儲爲三個字母 – novice

+1

明白了。至於國家,我忘了補充說,國家領域是指3個字母的縮寫。 – sstefan