0

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
3
  • Look at printf's format specifiers. Something like %02d would work to prefix a number with a 0. Keep in mind that how you store things in memory and how you display them don't need to be the same. Commented Nov 26, 2021 at 7:24
  • Is the input raw data or text? Commented Nov 26, 2021 at 7:34
  • @Lundin this is text data. Commented Nov 26, 2021 at 7:46

1 Answer 1

2

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("%02d", matrix[i][j]);  // Prints leading zero if value is only a single digit
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.