c - C fscanf 数据混乱
问题描述
我是编程新手,现在正在学习 C 语言。当我尝试从文件中读取数据并将它们存储在 char 数组中时,我遇到了问题。
我的输入是这样的:
Hayes,Darrell,Covey,Dasia,Hayes,Neftaly
Ashby,Angela,Chapman,Ebony,Ashby,Elliott
我的代码是这样的:
while(1) {
int ret = fscanf(fp," %[^,],%[^,],%[^,],%[^,],%[^,],%[^,]",
g_human_array[g_human_count].last_name,
g_human_array[g_human_count].first_name,
g_human_array[g_human_count].mother_last,
g_human_array[g_human_count].mother_first,
g_human_array[g_human_count].father_last,
g_human_array[g_human_count].father_first
);
printf("%s,%s,%s,%s,%s,%s,%d\n",
g_human_array[g_human_count].last_name,
g_human_array[g_human_count].first_name,
g_human_array[g_human_count].mother_last,
g_human_array[g_human_count].mother_first,
g_human_array[g_human_count].father_last,
g_human_array[g_human_count].father_first,ret
);
if(ret != 6) {
fclose(fp);
return READ_BAD_RECORD;
}
但是,我的输出是这样的:
Hayes,Darrell,Covey,Dasia,hby,Neftaly
Ashby,6
6
,,,,,,0
0
human_t 和 g_human_array 定义如下:
typedef struct human_struct {
char father_first[NAME_LENGTH];
char father_last[NAME_LENGTH];
char mother_first[NAME_LENGTH];
char mother_last[NAME_LENGTH];
char first_name[NAME_LENGTH];
char last_name[NAME_LENGTH];
} human_t;
human_t g_human_array[MAX_HUMANS];
解决方案
%[^,]
将匹配任何不包含逗号字符的字符串。这意味着换行符将包含在它匹配的字符串中,因此 last%[^,]
将匹配包含一行的最后一个字段和下一行的第一个字段的字符串。将其更改为%[^,\n]
使其不会跨换行符匹配。
int ret = fscanf(fp," %[^,],%[^,],%[^,],%[^,],%[^,],%[^,\n]",
g_human_array[g_human_count].last_name,
g_human_array[g_human_count].first_name,
g_human_array[g_human_count].mother_last,
g_human_array[g_human_count].mother_first,
g_human_array[g_human_count].father_last,
g_human_array[g_human_count].father_first
);
另一种解决方案是使用fgets()
一次读取一行,然后使用sscanf()
处理它。但是您仍然必须记住fgets()
将换行符留在缓冲区中,因此您必须在处理之前将其删除sscanf()
,或者\n
像我上面那样放入排除集。
推荐阅读
- python - Textblob 不能正确地复数/单数化动词
- java - controlling a java program from another java program on another node
- java - 从两个表中获取值,其中 invoice=?with join
- asp.net-mvc - 是 HttpClientFactory 错误吗?
- c++11 - 更大的作用是什么
在集? - reactjs - reactjs - 如何在formik中将状态值传递给初始值
- pom.xml - 错误:pom.xml 文档中没有这样的文件或目录
- amazon-sumerian - 减少 Sumerien IDE 更新时间滞后的方法
- javascript - 以函数方式从对象数组中的对象数组返回值
- c# - 任何字符组的正则表达式,范围从最小值到最大值