C fscanf数据混乱

时间:2018-10-17 21:58:14

标签: c scanf

我是编程新手,现在正在学习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];

1 个答案:

答案 0 :(得分:4)

%[^,]将匹配任何不包含逗号的字符串。这意味着换行符 将包含在它匹配的字符串中,因此最后一个%[^,]将匹配包含一个行的最后一个字段和下一行的第一个字段的字符串。将其更改为%[^,\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放入排除集中

相关问题