简体   繁体   中英

Reading from csv file and separating into variables in C

I've been looking for answer here, but didn't find solution for this particular problem.

I have this csv file

在此处输入图片说明

For imagination, I should have creating hockey players from this .csv file as

enum POZICE { UTOCNIK = 'U', OBRANCE = 'O', BRANKAR = 'B' };

typedef struct hrac {

int cislo;
char jmeno[50];
enum POZICE pozice;
int utocnaSila;
int obrannaSila;
struct hrac *dalsi;
} tHrac;

Number, name, position of player(keeper, defender, etc.), his attack power, defensive power and link to next player.

Creating method:

tHrac* vytvorHrace(int cislo, char* jmeno, enum Pozice pozice, int utocnaSila, int obrannaSila) {

tHrac* hrac = (tHrac*)malloc(sizeof(tHrac));
hrac->cislo = cislo;
strcpy(hrac->jmeno, jmeno);
hrac->pozice = pozice;
hrac->utocnaSila = utocnaSila;
hrac->obrannaSila = obrannaSila;
hrac->dalsi = NULL;

}

And now the core of my problem, loading method

void nactiSeznamHracu() {
char *tmp1[30];
char *tmp2[30];
char *tmp3[30];
char *tmp4[30];
char *ch[255];

int a = 0;

FILE* soubor = fopen(SEZNAM, "r");

fgets(ch, sizeof(ch), soubor);
fputs(ch, stdout);

sscanf(ch, "% [^;]%[^;]", tmp1, tmp2); // parsing whole char *ch into smaller pieces, wont work
puts(tmp1,tmp2);

fscanf(soubor, "%c [^;]%s [^;]", tmp3,tmp4); // without saving first line into ch, and cutting it right away
puts(tmp3);

//token = strtok(ch, "\n");
//puts(token);

}

I can succesfully load first line, but when I try somehow cut the lines into smaller pieces, like Number,Name,Attack,Deffence,Position, it won't work(or cutting only header into smaller pieces), I tried many ways, more than I've here, but result was always the same... (first two lines of img is unrelated, was just testing tHrac, creating and writing) 在此处输入图片说明

My intention is to create for cycle where it will load first line, load it seperately into variable which i will use to create tHrac and then it skip into next line and same thing ...

But my experience with C is low, so that's why I'm turning on you. Anyone can help?

sscanf(ch, "% [^;]%[^;]", tmp1, tmp2); // parsing whole char *ch into 
puts(tmp1,tmp2);
fscanf(soubor, "%c [^;]%s [^;]", tmp3,tmp4); 

tmp1 , tmp2 and all are array 30 of pointers to char , and passing wrong arguments would cause undefined behavior.

In case either you need to use individual pointer of these arrays after allocating memory to them ,

Or use them as array to char or char * , and you need to allocate memory in latter case and then pass them to sscanf or fscanf .

Note - Also you should check return value of sscanf and fscanf functions .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM