将 .csv 文件的值传递给结构向量
Pass the value of a .csv file to a struct vector
我有我的结构,我有那个结构的向量。另外,我有一个 .csv 文件,其中的数据用逗号分隔。
我需要做的是获取 .csv 文件每一行的每个值并将其放入我的结构向量中。每行对应一个不同的向量索引。
File.csv 型号
1,carlos,1232
321,patricia,212
5,james riko,23432
同一车道中的字段数量可能会有所不同,但始终仅以逗号分隔。
我使用 strtok()
做了一些事情,但我找不到用它填充结构的方法。
我的代码:
typedef struct{
int num_acc;
char name[25];
double value;
}struct_acc;
int main(){
FILE *arq_acc;
struct_acc acc[3];
char buffer[256];
char *pointer;
arq_acc = fopen("accs.csv", "r");
if(arq_acc == NULL){
printf("Error"); exit(0);}
while(pointer = fgets(buffer, sizeof(buffer), arq_acc) ){
char *token;
while( (token = strtok(pointer, ",") != NULL){
//Then I don't know how to fill the struct vector.
}
return 0;
}
我只是粘贴了我的旧代码,以向您展示我实际上正在尝试做一些事情。
我找不到用这段代码做我需要做的事情的方法,所以我可以获得完全不同的代码想法来实现我的目标。
在旧代码中,我需要重新启动循环以更改为当前车道的下一个值,然后我不能添加这样的内容:
while( (token = strtok(pointer, ",") ) != NULL ){
acc[0].num_acc = token;
// Now I need to set pointer as NULL and read the token again, to get the next value of the first row. But I can't do it like this. ;\
}
由于文件中的数据是统一的,可以使用sscanf
。跟踪指示要填充数组中的哪个帐户的索引。
sscanf(buffer, "%d,%24[^,],%lf",
&(acc[index].num_acc),
acc[index].name,
&(acc[index].value));
我有我的结构,我有那个结构的向量。另外,我有一个 .csv 文件,其中的数据用逗号分隔。
我需要做的是获取 .csv 文件每一行的每个值并将其放入我的结构向量中。每行对应一个不同的向量索引。
File.csv 型号
1,carlos,1232
321,patricia,212
5,james riko,23432
同一车道中的字段数量可能会有所不同,但始终仅以逗号分隔。
我使用 strtok()
做了一些事情,但我找不到用它填充结构的方法。
我的代码:
typedef struct{
int num_acc;
char name[25];
double value;
}struct_acc;
int main(){
FILE *arq_acc;
struct_acc acc[3];
char buffer[256];
char *pointer;
arq_acc = fopen("accs.csv", "r");
if(arq_acc == NULL){
printf("Error"); exit(0);}
while(pointer = fgets(buffer, sizeof(buffer), arq_acc) ){
char *token;
while( (token = strtok(pointer, ",") != NULL){
//Then I don't know how to fill the struct vector.
}
return 0;
}
我只是粘贴了我的旧代码,以向您展示我实际上正在尝试做一些事情。
我找不到用这段代码做我需要做的事情的方法,所以我可以获得完全不同的代码想法来实现我的目标。
在旧代码中,我需要重新启动循环以更改为当前车道的下一个值,然后我不能添加这样的内容:
while( (token = strtok(pointer, ",") ) != NULL ){
acc[0].num_acc = token;
// Now I need to set pointer as NULL and read the token again, to get the next value of the first row. But I can't do it like this. ;\
}
由于文件中的数据是统一的,可以使用sscanf
。跟踪指示要填充数组中的哪个帐户的索引。
sscanf(buffer, "%d,%24[^,],%lf",
&(acc[index].num_acc),
acc[index].name,
&(acc[index].value));