我有一个 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",""
我想将它放入二维字符串数组中(稍后我将忽略引号)。我尝试了许多不同的想法,但似乎无法正常工作。
此代码很接近,但输出以我无法理解的方式关闭。它还正确地解析和标记文件。将 token 放入数组时似乎变坏了。这是从我的程序中获取的代码:
#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 循环,您也会得到奇怪的输出。谢谢!
最佳答案
OP 是简单地记录读取缓冲区的地址,该地址会在后续读取时更新。
需要分配/复制字符串供以后使用。
// colors[i][j] = record;
colors[i][j] = strdup(record);
一行中剩余的 colors[i][j]
应设置为 NULL
。
while(j < VERTICES && record != NULL) {
printf(" %s", record);
colors[i][j] = strdup(record);
assert(colors[i][j]);
record = strtok(NULL, ",");
j++;
}
while(j < VERTICES) {
colors[i][j] = NULL;
j++;
}
健壮的代码还会检查分配失败 (assert(colors[i][j])
并在完成后释放内存。
关于c - 将字符串的 CSV 文件解析为二维字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37735396/