1
的二维数组我有一个字符串的CSV,看起来像这样:解析CSV文件转换成字符串
"","Orange","","","","","","Red",""
"Orange","","Blue","","","","","Black",""
"","Blue","","Pink","","Any","","","Any"
"","","Pink","","Green","Red","","",""
"","","","Green","","Blue","","",""
"","","Any","","BLue","","Orange","",""
"","","","Red","","Orange","","Green","Black"
"Red","Black","","","","","Green","","Yellow"
"","","Any","","","","Black","Yellow",""
,我想将其放入字符串二维数组(我会忽略稍后引号)。我尝试了许多不同的想法,但似乎无法正常工作。
这段代码很近,但输出关闭的方式我无法理解。它也可以正确解析和标记文件。它将令牌放入数组时似乎变得很糟糕。下面是我的程序所采取的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define VERTICES 9
int main(void)
{
const char *colors[VERTICES][VERTICES];
char buffer[1024];
char *record, *line;
int i = 0;
int j = 0;
FILE *fstream = fopen("Colors.dat", "r");
if (fstream == NULL)
{
printf("\n file opening failed\n");
return -1;
}
while ((line = fgets(buffer, sizeof(buffer), fstream)) != NULL)
{
record = strtok(line, ",");
while(record != NULL)
{
printf(" %s", record);
colors[i][j] = record;
//printf(" %s"), colors[i][j];
record = strtok(NULL, ",");
j++;
}
j = 0;
++i;
}
printf("\n============================================\n\n");
for (i = 0; i < VERTICES; i++)
{
for (j = 0; j < VERTICES; j++)
{
printf("%s | ", colors[i][j]);
}
printf("\n");
}
return 0;
}
如果取消对该行的第二嵌套while循环和注释掉两个for循环你奇数输出为好。谢谢!
也许像'颜色[i] [j] =记录;' - >'颜色[我] [j] = strdup(record);'''colors',就像现在使用的那样,只是将指针填入'buffer'。 – chux
@chux哇,这可能已经完成了。你想把它放在回答? – ddschmitz