fscanf 函数不会在 c 中读取
fscanf function doesn't read in c
我尝试从文件中读取一些数据并将其插入到队列中,插入功能运行良好,并且我尝试使用 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
需要 int*
,而不是一个 int
。我使用了 == 2
以便在 EOF
或无效数据(如字符)的情况下循环中断。否则,如果文件包含无效数据,循环将变成无限循环,因为 %d
将无法扫描整数。
您还应该检查 fopen
是否成功。 fopen
returns NULL
失败。
您必须将 指针 传递到 fscanf()
存储值的位置,并检查所有预期的转换是否成功:
while (fscanf(fp, "%d %d", &natid, &cond) == 2)
我尝试从文件中读取一些数据并将其插入到队列中,插入功能运行良好,并且我尝试使用 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
需要 int*
,而不是一个 int
。我使用了 == 2
以便在 EOF
或无效数据(如字符)的情况下循环中断。否则,如果文件包含无效数据,循环将变成无限循环,因为 %d
将无法扫描整数。
您还应该检查
fopen
是否成功。 fopen
returns NULL
失败。
您必须将 指针 传递到 fscanf()
存储值的位置,并检查所有预期的转换是否成功:
while (fscanf(fp, "%d %d", &natid, &cond) == 2)