首页 > 解决方案 > fscanf() 函数在读取的第一个字符处放置一个 \000

问题描述

我试图读取这种格式的文件:

05874121 A 7
07894544 C 3
05655454 B 5
05879544 B 6
05763465 C 2

并将每个“单词”分配给不同的变量(dni、模型、垃圾)

此代码在 Linux 上运行,我使用 CLion 进行调试。

char *path = "file.txt";
FILE *f;
int result;
char dni[9], model[1], trash[100];

f = fopen(path, "r");
do {
    result = fscanf(f, "%s %s %s", dni, model, trash);
    printf("DNI: %s\n", dni);
}
while( result > 0);

fclose(f);

这应该打印第一列的值,但是当我执行程序时,输出只是:“DNI:”“DNI:”“DNI:”......等等。

在调试时,我意识到“dni”正确地存储了所有数字(作为字符),但是第一个元素 dni[0] 总是:0 '/000' 就像它是字符串的结尾一样。

我不知道为什么会这样。

标签: c

解决方案


我在您的代码中做了 2 处更正:

#include <stdio.h>
int main (int argc, char ** argv) {
        char *path = "file.txt";
        FILE *f;
        int result;
        char dni[9], model[2], trash[100];

        f = fopen(path, "r");
        while(1) {
            result = fscanf(f, "%s %s %s", dni, model, trash);
            if (result < 1) break;
            printf("DNI: %s model %s trash %s\n", dni, model, trash);
        }

        fclose(f);
        return 0;
}

首先,变量 model[2] 必须有一个额外的字符作为字符串的结尾。

然后,行“if (result <1) break;”。

Probably, the error was the model[1] with only one character. The \ 000 in dni can be the end of the model string.


推荐阅读