I have a struct like so:
struct Office {
char city[50];
int employees;
char desc[200];
}
struct Office office[100];
Then I want to fill the office array within a loop until reach end of file.
here is my data:
Toronto
151: This is HQ
Vancouver
23: This is branch office
London
12: This is euro branch
Take this as an example:
Toronto
151: This is HQ
So here I want to parse it to struct:
city = "Toronto"
employees = 151
desc = "This is HQ"
Notice: After city name in the new line before the number of employess, there is TAB (4 spaces)
I have had an implementation like so, but seems it does not work properly:
int function LoadOffices(const char *f) {
int res = 1;
char buf[500];
char city[50];
int emp;
char desc[200];
struct Office offices[100];
FILE *fp = fopen(f, "r");
if (fp) {
while (fgets(buf, sizeof(line), fp) != nullptr) {
if (i == 0) {
rewind(fp);
}
i++;
if (fscanf(fp, "%[^\n]", city) == 1) {
strncpy(offices[i].city, city, 50);
} else if (fscanf(fp, "%d[^:]:%[^\n]", &emp, desc) == 2) {
offices[i].employees = emp;
strncpy(offices[i].desc, desc, 200);
}
}
res = 0;
} else {
res = 1;
}
fclose(fp);
return res;
}
I just want to know how to deal with TAB and empty lines
Aucun commentaire:
Enregistrer un commentaire