繁体   English   中英

fscanf函数无法在c中读取

[英]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)

您需要传递natidcond的地址而不是其值,因为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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM