fscanf() 读取失败

问题描述 投票:0回答:1
    int ingatlanazonosito, alapterulet, emelet, szobak_szama, rezsi, berleti_dij;
    double x, y;
    char cim[300], butorozott[13];

    while (fscanf(ingatlanfile,"%d;%[^;];%lf;%lf;%d;%d;%d;%[^;];%d;%d\n",
            &ingatlanazonosito, cim, &x, &y, &alapterulet, &emelet,
            &szobak_szama, butorozott, &rezsi, &berleti_dij) != EOF)
    {
        ingatlanbeszur(&ingatlanok, ingatlanazonosito, cim, x, y,
            alapterulet, emelet, szobak_szama, butorozott, rezsi,
            berleti_dij);
    }

我对上面列出的代码有问题,问题是

fscanf
无法读取第二个字符串(
%[^;]
)及其后面的所有内容。我正确打开文件,第二个字符串之前的所有内容都是正确的。
butorozott
字符串充满了 s。 这是在
ingatlanfile
文本文件中:

123456;Irinyi Jozsef u.;47.473;19.053;18;15;butorozott;1000;9500

我该如何解决这个问题?

c scanf
1个回答
0
投票

输入行在第一个字符串之后不包含 3 个整数,因此

fscanf
无法转换第 7 个字段并返回
6
而不是预期的
10
字段。

您应该使用

fgets()
一次读取一整行,并使用
sscanf()
尝试转换,在失败时生成一条信息性错误消息:

    char buf[500];
    int ingatlanazonosito, alapterulet, emelet, szobak_szama, rezsi, berleti_dij;
    double x, y;
    char cim[300], butorozott[13];

    while (fgets(buf, sizeof buf, ingatlanfile)) {
        int n = sscanf(buf, "%d;%[^;];%lf;%lf;%d;%d;%d;%[^;];%d;%d\n",
                       &ingatlanazonosito, cim, &x, &y, &alapterulet,
                       &emelet, &szobak_szama, butorozott,
                       &rezsi, &berleti_dij);
        if (n != 10) {
            fprintf(stderr, "conversion error for field %d: %s\n", n + 1, buf);
             continue;  // or some other error recovery decision
        }
        ingatlanbeszur(&ingatlanok, ingatlanazonosito, cim, x, y,
                       alapterulet, emelet, szobak_szama, butorozott,
                       rezsi, berleti_dij);
    }
© www.soinside.com 2019 - 2024. All rights reserved.