【发布时间】:2016-10-19 15:32:07
【问题描述】:
fscanf 函数有问题。我是C新手,我想从文件中读取行并将它们保存到结构中,但似乎我不太了解它^^。
PATIENT *patientTab;
int tabSize = 0;
int patientCount = 0;
PATIENT temp;
int tempIndex = 0;
if (openFile()){
printf("Plik otworzony!\n\n");
while(fscanf(dataBase, "%s %f",
&temp.patientNumber,
&temp.patientGender,
&temp.patientLength,
&temp.patientWeigth,
&temp.patientHeadCircuit,
&temp.patientApperance,
&temp.patientPulse,
&temp.patientGrimace,
&temp.patientActivity,
&temp.patientRespiration)
!= EOF){
if (patientCount + 1 >= tabSize){
tabSize += 5;
patientTab = realloc(patientTab, sizeof(int) * tabSize);
}
for (tempIndex; tempIndex < 5; tempIndex++){
patientTab[patientCount].patientNumber[tempIndex] = temp.patientNumber[tempIndex];
}
patientTab[patientCount].patientGender = temp.patientGender;
patientTab[patientCount].patientLength = temp.patientLength;
patientTab[patientCount].patientWeigth = temp.patientLength;
patientTab[patientCount].patientHeadCircuit = temp.patientHeadCircuit;
patientTab[patientCount].patientApperance = temp.patientApperance;
patientTab[patientCount].patientPulse = temp.patientPulse;
patientTab[patientCount].patientGrimace = temp.patientGrimace;
patientTab[patientCount].patientActivity = temp.patientActivity;
patientTab[patientCount].patientRespiration = temp.patientRespiration;
patientCount++;
}
//free(temp);
fclose(dataBase);
}
else endProgram();
数据库是全局的。
问题是当程序试图循环“while”,其中包括“fscanf”函数时,程序正在抛出一个错误,我唯一能做的就是关闭程序。我在互联网上找到了一个示例,但这是一个带有一个变量的简单示例。我确定问题出在我的声明中带有许多带有“&temp”的参数。
结构是:
typedef struct Patient {
char patientNumber[5];
char patientGender;
double patientLength;
float patientWeigth;
float patientHeadCircuit;
int patientApperance;
int patientPulse;
int patientGrimace;
int patientActivity;
int patientRespiration;
}PATIENT;
...这是内容文件的片段: txt link
【问题讨论】:
-
这是什么烂摊子?您的
scanf格式字符串仅用于两个参数。而你正在像无数人一样过去。 -
该结构的所有其他成员的值将是不确定的,因为结构
temp未初始化。 UB。 -
我不明白你只用两个格式标签读入10变量是什么意思:
while(fscanf(dataBase, "%s %f", &temp.patientNumber, &temp.patientGender, &temp.patientLength, &temp.patientWeigth, &temp.patientHeadCircuit, &temp.patientApperance, &temp.patientPulse, &temp.patientGrimace, &temp.patientActivity, &temp.patientRespiration)? -
%fforpatientGender?嗯......这是一个假设;) -
使用 %s 读取患者编号(声明为 char[5])是危险的。如果输入的字符超过 4 个怎么办? (答案:你会在分配的空间之外写)。