[英]fscanf() function puts a \000 at the first char read
Im trying to read a file with this format: 我试图用这种格式读取文件:
05874121 A 7
07894544 C 3
05655454 B 5
05879544 B 6
05763465 C 2
and assign each 'word' to different variables (dni, model, trash) 并将每个'单词'分配给不同的变量(dni,model,trash)
This code is running on Linux, and I use CLion for debugging. 这段代码在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);
This should print the first column values, but when I execute the program, the output is just: "DNI: " "DNI: " "DNI: " ... and so on. 这应该打印第一列值,但是当我执行程序时,输出只是:“DNI:”“DNI:”“DNI:”......依此类推。
While debugging, I realized that "dni" store correctly all the numbers (as chars), but the very first element, dni[0], is always: 0 '/000' like if it was the end of the string. 在调试时,我意识到“dni”正确存储了所有数字(作为字符),但第一个元素dni [0]始终为:0'/ 000',就好像它是字符串的结尾一样。
I dont know why is happening this. 我不知道为什么会发生这种情况。
I did 2 corrections in your code: 我在你的代码中做了两次更正:
#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;
}
First, the variable model[2] must have an extra character for the end of the string. 首先,变量model [2]必须在字符串的末尾有一个额外的字符。
Then, the line "if (result <1) break;". 然后,行“if(result <1)break;”。
Probably, the error was the model[1] with only one character. 可能是错误是只有一个字符的模型[1]。 The \\ 000 in dni can be the end of the model string.
dni中的\\ 000可以是模型字符串的结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.