Diablo Diablo - 2 months ago 7
C Question

Content from TSV file into a Multi-Deimensional Array

I have been given a TSV file.
I am reading through it using a getchar() function and I enter program < testfile.tsv into my command line when running my function.

while ((c=getchar()) != EOF) {


I am able to read through it but i dont know how to store the strings in a multidimensional array. How to make an array that would be A[ROW][COLUMN]?

Sample Input(\t is tab, \n is newline):

Anything\tIs\tPossible\tYay\n

What\tDo\tI\tDo\n

This\tis\tgreat\twow\n

This is what I tried doing.

if (c == '\t') {
columncount += 1;
A[rowcount][columncount] = c;

};
if (c == '\n') {
columncount += 1;
A[rowcount][columncount] = c;
rowcount += 1;
columncount = 0;
}

Answer

It's simple: When you read a tab you increase the index variable used for column, and when you read a newline you reset the column index and increase the line index variable.

You should make sure that the index variables are properly initialized before you start reading, and that you don't go out of bounds when incrementing the variables.

Also don't forget to terminate the strings when you get a tab or newline. Don't put the tab or newline character in the strings.

Finally, you need an array of arrays of arrays, i.e.

char A[ROWS][COLUMNS][MAX_LENGTH_OF_STRINGS];

Translated into code, you could do something like

int c;
int row = 0;
int column = 0;
int string_index = 0;

while ((c = getchar()) != EOF)
{
    if (c == '\t')
    {
        A[row][column++][string_index] = '\0' // Terminate the string
        string_index = 0;
    }
    else if (c == '\n')
    {
        A[row++][column][string_index] = '\0' // Terminate the string
        string_index = 0;
        column = 0;
    }
    else
    {
        if (string_index >= MAX_LENGTH_OF_STRINGS)
        {
            printf("Error: String to long at row %d, column %d\n", row, column);
            break;
        }
        if (row >= ROW)
        {
            printf("Error: row is to large: %d\n", row);
            break;
        }
        if (column >= COLUMN)
        {
            printf("Error: column is to large: %d (at row %d)\n", column ,row);
            break;
        }

        A[row][column][string_index++] = c;
    }
}

Now to do something with the loaded texts, how about printing it?

for (row = 0; row < ROW; ++row)
{
    for (column = 0; column < COLUMN; ++column)
    {
        printf("A[%d][%d] = %s\n", row, column, A[row][column]);
    }
}