Home > database >  How would I create a 2D array of strings of numbers in C?
How would I create a 2D array of strings of numbers in C?

Time:11-27

I'm working an assignment and I'm relatively new to C. If I were to be given an input file like this:

25 08 10 15 10 
10 13 50 60 70 
10 10 15 00 90
00 05 07 80 12
10 05 60 70 88

How would I correctly store these in an array such that it's displayed like a 2D array or is that not possible in the way I'm thinking with C.

The code I have below is a function for converting the input file into a 2d array. Assuming that I have already other functions error checking if the file is in the correct format.

void createMatrix(FILE *fp) {
    int row = 5;
    int col = 5;
    char matrix[row][col];
    int i, j;
    char num[25];

    rewind(fp);
    for (i=0; i<row; i  ) {
        for(j=0; j<col; j  ) {
            fscanf(fp, "%s", name);
            bingoCard[i][j] = name;
        }
    }
}

This would work if it was integers I'm looking for but I need to preserve the 0's in front of numbers like 00 or 08. I also later need to append to these numbers which is why I need to get them in an array in a string format. Would anyone be able to point me in the right direction?

I would then need to print the input file when making updates to it like this

25X 08 10 15 10 
10  13 50 60 70 
10  10 15 00 90
00  05 07 80 12
10  05 60 70 88

CodePudding user response:

Make each element in the matrix a string (an array). E.g.

char matrix[row][col][10];

Then read into that string directly:

fscanf(fp, "%9s", matrix[i][j]);

But you could also create your matrix as a matrix of integers and then use printf formatting to include leading zeros:

int matrix[row][col];
// ...
fscanf(fp, "%d", &matrix[i][j]);
// ...
printf("d", matrix[i][j]);  // Prints leading zero if value is only a single digit
  • Related