我有这个结构学生记录,我想暂时填写来自两个文件NamesIDsDataFile和MarksDataFile的值,但是当我运行循环时,只有来自NamesIDsDataFile的值进入结构。我将print语句放在while循环中以查看问题是什么,当我运行代码时没有打印出来。有人可以解释如何从MarksDataFile打印值。
struct StudentRecord {
char FirstNames[MAXLENGTH];
char LastNames[MAXLENGTH];
int IDNums;
int Marks;
};
FILE * NamesIDsDataFile;
FILE * MarksDataFile;
while (fscanf(NamesIDsDataFile,"%s%s%d",&(SRecords.FirstNames[0]),
&(SRecords.LastNames[0]), &(SRecords.IDNums)) != EOF) {
fscanf(MarksDataFile,"%d",&(SRecords.Marks));
printf("%d", SRecords.Marks);
}
fclose(NamesIDsDataFile);
fclose(MarksDataFile);
答案 0 :(得分:0)
通过对代码进行少许更改的简单方法是:
while (fscanf(NamesIDsDataFile," %s %s %d ",&(SRecords.FirstNames[0]),
&(SRecords.LastNames[0]), &(SRecords.IDNums)) != EOF)
{
fscanf(MarksDataFile," %d ",&(SRecords.Marks));
printf("%d", SRecords.Marks);
}
但是,如果文本文件不总是相同且结构不是很好,则不应使用上面的代码,而应使用以下代码。
这是最好的方法:
int ret1,ret2;
while (ret =fscanf(NamesIDsDataFile," %s %s %d ",&(SRecords.FirstNames[0]),
&(SRecords.LastNames[0]), &(SRecords.IDNums))) {
if(ret == EOF)
{
break;
}
else
{
ret2 = fscanf(MarksDataFile," %d ",&(SRecords.Marks));
if(ret2 == EOF || ret2 == 0)
{
break;
}else
{
printf("%d", SRecords.Marks);
}
}
}
fclose(NamesIDsDataFile);
fclose(MarksDataFile);
ret是一个int变量,其值为: