繁体   English   中英

fscanf()函数在第一个char读取时放置一个\\ 000

[英]fscanf() function puts a \000 at the first char read

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

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

并将每个'单词'分配给不同的变量(dni,model,trash)

这段代码在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',就好像它是字符串的结尾一样。

我不知道为什么会发生这种情况。

我在你的代码中做了两次更正:

#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;”。

可能是错误是只有一个字符的模型[1]。 dni中的\\ 000可以是模型字符串的结尾。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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