我尝试从文件中读取一些数据并将其插入到队列中,插入函数运行良好,并试图用printfs捕获错误。我在时间()行中看到了错误。这样的文件格式中的数据
12345 2
11232 4
22311 4
22231 2
void read_file(struct Queue *head){
FILE *fp;
int natid;
int cond;
fp=fopen("patients.txt","r");
while (fscanf(fp,"%d %d", natid, cond) != EOF)
insert(head,natid,cond);
fclose(fp);}发布于 2015-05-08 14:08:51
必须将指针传递到fscanf()存储值的位置,并检查所有预期转换是否成功:
while (fscanf(fp, "%d %d", &natid, &cond) == 2)发布于 2015-05-08 14:08:26
while (fscanf(fp,"%d %d", natid, cond) != EOF)应该是
while (fscanf(fp,"%d %d", &natid, &cond) == 2)您需要传递natid和cond的地址,而不是它的值,因为fscanf中的%d要求的是int*,而不是int。我使用了== 2,以便在EOF或无效数据(如字符)情况下循环中断。否则,如果文件包含无效数据,则循环将变成无限循环,因为%d将无法扫描整数。
您还应该检查fopen是否成功。fopen在失败时返回NULL。
https://stackoverflow.com/questions/30125846
复制相似问题