我的csv文件看起来像这样:
爱丽丝,女孩,19,美容
艾力,, 30,冷
现在如上例所示,第二个条目中有两个逗号。现在我在c中使用以下说明来读取csv并将其存储在数据结构中'数据':
fscanf(filename,"%[^,],%[^,],%d, %[^,]", data.name,data.gender,&data.age,data.att);
如何忽略第二个逗号?有什么方法可以写%[^,^,]
来容纳2个逗号吗?
任何帮助将不胜感激!谢谢!
答案 0 :(得分:2)
使用strsep
的示例(省略检查)
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
//Implementation as an example as it is not a standard function
//It is unnecessary when it is usable
char *strsep(char **sp, const char *sep){
char *p, *s;
if (sp == NULL || *sp == NULL || **sp == '\0') return NULL;
s = *sp;
p = s + strcspn(s, sep);
if (*p != '\0') *p++ = '\0';
*sp = p;
return s;
}
typedef struct data {
char name[32];
char gender[8];
int age;
char att[96];
} Data;
int main(void){
const char *filename = "data.csv";
FILE *fp = fopen(filename, "r");
Data data;
char buff[128];
char *token, *p;
while(fgets(buff, sizeof(buff), fp)){
p = buff;
token = strsep(&p, ",\n");//1st field
strcpy(data.name, token);
token = strsep(&p, ",\n");//2nd field
strcpy(data.gender, token);
token = strsep(&p, ",\n");//3rd field
data.age = atoi(token);
token = strsep(&p, ",\n");//4th field
strcpy(data.att, token);
//check print
printf("DEBUG:\nName:'%s', Gender:'%s', Age:%d, Attribute:'%s'\n",
data.name, data.gender, data.age, data.att);
}
fclose(fp);
}