I have a CSV of strings that looks like so:
"","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",""
and I would like to place it into a 2d array of strings (I'll ignore the quotation marks later). I've tried many different ideas but can't seem to get any to work properly.
This code is close but the output is off in a way I can't make sense of. It also parses and tokenizes the file correctly. It seems to go bad when it puts the tokens into the array. Here is the code taken from my program:
#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;
}
If you uncomment the line in the second nested while loop and comment out the two for loops you get odd output as well. Thanks!
colors[i][j] = record;-->colors[i][j] = strdup(record);?colors, as now used, is just fill with pointers intobuffer.