[英]C File Parsing Issue
I have a file to read in that is in a format like 我有一个要读取的文件,其格式为
3%6%1 3%6%1
5%3%0 5%3%0
4%9%2 4%9%2
I need it in some format where I can save the separate fields from each line, like I suppose I can make a typedef SOMETHING with SOMETHING.num1 = 3, SOMETHING.num2 = 6, SOMETHING.num3 = 1 我需要以某种格式保存每个行中的单独字段,例如我想可以使用SOMETHING.num1 = 3,SOMETHING.num2 = 6,SOMETHING.num3 = 1来创建typedef SOMETHING
Here's what I have so far: 这是我到目前为止的内容:
#define BUF 128
#define LINES 100
char line[LINES][BUF];
FILE *input = NULL;
int i = 0;
int total = 0;
input = fopen("input.txt", "r");
while(fgets(line[i], BUF, input))
{
/* get rid of ending \n from fgets */
line[i][strlen(line[i]) - 1] = '\0';
i++;
}
total = i;
printf("ORIGINAL READ:\n");
for(i = 0; i < total; ++i)
{
printf("%s\n", line[i]);
}
printf("\nPARSED:\n");
char *token;
char parsed[LINES][BUF];
for(i=0; i<total; i++)
{
token = strtok(line[i], "%");
while(token != NULL)
{
strcpy(parsed[i],token);
token = strtok(NULL, "%");
}
}
for(i=0; i<total; i++)
{
printf("%s\n",parsed[i]);
}
The problem is when I print out the values in my parsed array, it seems to only have the last value of each line, (ie for the sample ^ it would output 1,0,2). 问题是当我打印出解析数组中的值时,似乎只有每行的最后一个值(即对于示例^,它将输出1,0,2)。 I'm new to C programming, how can I go about this? 我是C编程的新手,我该怎么办?
Right now you are using i
to index your parsed numbers, but i
is also your line index. 现在,您正在使用i
来索引已解析的数字,但是i
也是您的行索引。 You need a separate index to keep track of the numbers you have parsed. 您需要一个单独的索引来跟踪已解析的数字。
int numberCount = 0;
...
strcpy(parsed[numberCount++],token);
...
for(i=0; i<numberCount; i++)
printf("%s\n",parsed[i]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.