[英]fscanf function doesn't read in c
我试图从文件中读取一些数据并将其插入队列,Insert函数运行良好,并且我尝试使用printfs捕获错误。 我在while()行中看到错误。 像这样的文件形式的数据
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);}
while (fscanf(fp,"%d %d", natid, cond) != EOF)
应该
while (fscanf(fp,"%d %d", &natid, &cond) == 2)
您需要传递natid
和cond
的地址而不是其值,因为fscanf
的%d
s需要一个int*
,而不是int
。 而且我使用== 2
以便在EOF
或无效数据(例如字符)的情况下中断循环。 否则,如果文件包含无效数据,则循环将变成无限循环,因为%d
将无法扫描整数。
fopen
是否成功。
如果失败, fopen
将返回NULL
。
您必须将指针传递到fscanf()
将存储值的位置,并检查所有预期的转换是否成功:
while (fscanf(fp, "%d %d", &natid, &cond) == 2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.