【问题标题】:fscanf function doesn't read in cfscanf 函数未在 c 中读取
【发布时间】:2015-07-19 11:43:42
【问题描述】:

我尝试从文件中读取一些数据并将其插入队列,插入功能运行良好,我尝试使用 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);}

【问题讨论】:

    标签: c file-io scanf


    【解决方案1】:

    您必须将指针传递到fscanf() 应存储值的位置,并检查所有预期的转换是否成功:

    while (fscanf(fp, "%d %d", &natid, &cond) == 2)
    

    【讨论】:

    • 感谢您的回答。我做了你说的,但现在它只读取第一行。 fscanf 未读取 12345 2 以下的下一行。
    【解决方案2】:
    while (fscanf(fp,"%d %d", natid, cond) != EOF)
    

    应该是

    while (fscanf(fp,"%d %d", &natid, &cond) == 2)
    

    您需要传递natidcond 的地址而不是其值,因为fscanf 中的%ds 需要int*,而不是int。而且我使用了== 2,以便在EOF 或无效数据(如字符)的情况下循环中断。否则,如果文件包含无效数据,则循环将变为无限循环,因为%d 将无法扫描整数。


    您还应该检查fopen 是否成功。 fopen 失败时返回 NULL

    【讨论】:

    • 成功了,我检查了 fopen 并做了你所说的 while 循环。它现在只读取第一行。
    • @Y.E.S. , 那不应该发生。尝试将insert(head,natid,cond); 替换为printf("%d %d scanned", natid, cond);,以确保所有内容都在被扫描。我认为问题出在insert
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2018-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多