2016-05-27 207 views
1

这是一段代码。基本上,第一个“while”部分中的列表中的学生数量和按照统计的数量进行分配。并保存到结构。 但问题是:首先“while”作为无限循环运行?无限循环和结构

int t=0; 

FILE *exam; 

struct str_examrecords_table 
{ 
    int id_number; 
    char result; 
}; 


void Load_examrecords_table(struct str_examrecords_table *examrecords_table) 
{ 
    char temporary_char; 
    int temporary_int, i=0; 

    exam=fopen("examrecords.odt","r"); 

    if(exam!=NULL) 
    { 
     while(fscanf(exam, "%d %c", &temporary_int, &temporary_char)!=EOF) 
     t++; 

     examrecords_table = (struct str_examrecords_table *) malloc(sizeof(struct str_examrecords_table) * t); 

     while(fscanf(exam, "%d %c", &examrecords_table[i].id_number, &examrecords_table[i].result)!=EOF)  
     i++; 
    } 
    else exit(1); 

    for(int j=0; j<i; j++) 
    printf("%d %c \n", examrecords_table[i].id_number, examrecords_table[i].result); 

    fclose(exam); 
} 


int main() 
{ 
    struct str_examrecords_table *examrecords_table; 
    Load_examrecords_table(examrecords_table); 

    system("pause"); 
    return 0; 
} 

回答

2

从​​:

如果第一转换成功或匹配故障发生之前达到输入的端部的返回值EOF。

而且

这些函数返回成功匹配,并分配输入项目,其可为少于规定的,或甚至零在早期匹配失败的情况下的数量。

所以将其更改为:

while(fscanf(exam, "%d %c", &temporary_int, &temporary_char) == 2)

+0

同意,但我认为你的意思''==不是'='!。 – FatalError

+0

@FatalError是的。 C&P错误;)Tx。 – LPs

2

this文档的fscanf返回值指示读取的物品,文件不是一个可能的最终数量。