Reputation: 315
This is a really fascinating error to me, because literally an hour ago this code was working just fine, but now it's not.
Essentially what is happening is that the first character of first 'block' of the following row is being appended as the last character of the final 'block'
Whereby 'block' I mean the string that is held within that row/col.
For example, let's say that the array is supposed to be something like
1,2,3,Hello
4,5,6,Wonder
It is being read in as
1,2,3,Hello4,
6,Wonder, ,
Here's the logic that I've been using. I really don't know what changed, so any advice would be excellent.
tableFile = fopen(argv[4], "r");
//pulling the table data from the file
char tableArray[30][50][256];
char c;
int i=0, j=0, k=0;
while(c != EOF){
c = fgetc(tableFile);
switch(c)
{
case ',':
tableArray[i][j++][k]='\0';
k=0;
break;
case '\n':
tableArray[i++][j][k]='\0';
j=0;
k=0;
break;
case '\r':
break;
case EOF:
break;
default:
tableArray[i][j][k++] = c;
break;
}
} //end file transfer
//Just to display, ignore magic numbers as (mostly) irrelevant
int a, b;
for (a = 0; a < 20; a++)
{
for (b = 0; b < 47; b++)
{
printf ("%s", tableArray[a][b]);
if (b<46)
printf (", ");
}
printf ("\n");
}
fclose(tableFile);
Upvotes: 2
Views: 1033
Reputation: 315
This is really due to the comments immediately below my original post. But, as disgusting and poor coding form as it is... this is what solved it consistently, not that I'm proud of it... and still open to ideas:
tableFile = fopen(argv[4], "r");
//pulling the table data from the file, lazy magic numbers here...
char tableArray[30][50][256];
char c;
int i=0, j=0, k=0;
memset(tableArray, 0, sizeof(tableArray));
while(c != EOF){
c = fgetc(tableFile);
switch(c)
{
case ',':
tableArray[i][j++][k]='\0';
k=0;
break;
case '\n':
tableArray[i++][j][k]='\0';
j=0;
k=0;
break;
case '\r':
tableArray[i++][j][k]='\0';
j=0;
k=0;
break;
case EOF:
tableArray[i][j][k] = '\0';
break;
default:
tableArray[i][j][k++] = c;
break;
}
} //end file transfer
/* //Only relevant for displaying the tableArray
int a, b;
for (a = 0; a < 20; a++)
{
for (b = 0; b < 47; b++)
{
printf ("%s", tableArray[a][b]);
if (b<46)
printf (", ");
}
printf ("\n");
}
*/
fclose(tableFile);
Upvotes: 0
Reputation: 22542
You did not initialise your array. It is not guaranteed to come zero filled. add
memset(tableArray, 0, sizeof(tableArray))
case EOF:
has to add a NULL
terminator to the most recent string.
Upvotes: 1