c - 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' 就像它是字符串的结尾一样。
我不知道为什么会这样。
解决方案
我在您的代码中做了 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.
推荐阅读
- r - 无法在 R 中安装任何软件包
- javascript - 任何模块都支持 npx,如 argv 解析器?
- android-studio - 如何捕获intellij插件卸载事件
- bash - 在 .csv 文件中选择列名
- google-apps-script - 从 Google Visualization API 查询中获取行号到 Google Sheet
- r - dplyr select 声称我有额外的参数不存在
- android - 如何消除“Rooms Repository”object.getInstance(app)的危险?
- swift - 添加到场景时,Swift SpriteKit SKEmitter 节点颜色不正确
- google-cloud-shell - 带有 ?authuser=1 参数的谷歌云外壳不断加载
- list - 给定位置可以采用的元素,生成所有可能列表的列表的函数