【发布时间】:2016-03-14 19:31:13
【问题描述】:
大家好,我正在读取一个文件并希望将数据解析为一个结构数组。该文件如下所示:
Country,City,Area Code,Population
China,Beijing,,21256972
France,Paris,334,3568253
Italy,Rome,,1235682
我想解析数据并将成员分配给文件中的每个区域。我在解析第 1 行和第 3 行的数据时没有问题。但是如果没有区号并且彼此相邻有两个逗号,则令牌变为空,并且出现错误。我一直在寻找,似乎无法找到解决方案。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
static struct Locations {
char country[20];
char city[20];
char areaCode[5];
char population[100];
} line[2000000];
// open file
FILE *Lfile;
Lfile = fopen("locations.txt", "r");
if (!Lfile) {
perror("File Error");
}
char buf[100];
const char delim[2] = ",";
char *token;
int i = 0;
while (fgets(buf, 100, Lfile) != NULL) {
token = strtok(buf, delim);
while (token != NULL) {
strcpy(line[i].country, token);
token = strtok(NULL, delim);
strcpy(line[i].city, token);
token = strtok(NULL, delim);
strcpy(line[i].areaCode, token); //Error here
token = strtok(NULL, delim);
strcpy(line[i].population, token);
token = strtok(NULL, delim);
}
printf("%s %s %s %s\n", line[i].country,
line[i].city, line[i].areaCode, line[i].population);
i++;
}
return 0;
}
【问题讨论】:
标签: c parsing struct token delimiter