首页 > 解决方案 > 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];

标签: cscanf

解决方案


%[^,]将匹配任何不包含逗号字符的字符串。这意味着换行符包含在它匹配的字符串中,因此 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像我上面那样放入排除集。


推荐阅读