1

I'm trying to read the input of a file that has something like

RGGG
RGYY 
YYYY

So, I'm trying to get a string array with each of the mentioned strings (and more if so want to). So far, I got my input into a 2d array, yet I can't seem to figure out out to place the read chars into a string array.

char ch, file_name[100];
FILE *fp;

printf("Enter the name of file you wish to see\n");
scanf("%s", file_name);

fp = fopen(file_name, "r"); // read mode

if (fp == NULL) {
    perror("Error while opening the file.\n");
    exit(EXIT_FAILURE);
}

printf("The contents of %s file are :\n", file_name);

Matrix = (char **)malloc(4 * sizeof(char *));
for (int i = 0; i < 4; i++)
    Matrix[i] = (char*)malloc(8 * sizeof(char));

for (int i = 0; i < 4; i++) {
    int j = 0;
    while (j < 4 && fscanf(fp, "%c", &Matrix[i][j++]) == 1);
}

for (i = 0; i < 4; i++) {
    for (j = 0; j < 8; j++) {
        printf("Matrix[%d][%d] = %c\n", i, j, Matrix[i][j]);
    }
}

And this is printing something like:

Matriz[0][0] = R
Matriz[0][1] = G
Matriz[0][2] = G
Matriz[0][3] = G
Matriz[0][4] =

Matriz[0][5] = R
Matriz[0][6] = G
Matriz[0][7] = Y
Matriz[1][0] = Y
Matriz[1][1] =

Matriz[1][2] = Y
Matriz[1][3] = Y
Matriz[1][4] = Y
Matriz[1][5] = Y
Matriz[1][6] = ═
Matriz[1][7] = ═

Would apreciate some insight on getting :

string[0] = RGGG
string[1] = RGYY
string[2] = YYYY

Am I just missing something really obvious? Thanks.

1
  • This has been answered a number of times. See return 2d array from function for starters. Use line-oriented input functions for reading lines of data... Commented Jan 15, 2016 at 2:14

1 Answer 1

1

You should skip the '\n' at the end of each line:

for (int i = 0; i < 4; i++) {
    int j = 0;
    while (j < 4 && fscanf(fp, "%c", &Matrix[i][j++]) == 1);
    getc(fp);
}

Or simpler:

for (int i = 0; i < 4; i++) {
    memset(Matrix[i], 0, 8);
    fscanf(fp, "%7s", Matrix[i]);
}

And dump the strings this way:

for (int i = 0; i < 4; i++) {
    printf("Matrix[%d] = %s\n", i, Matrix[i]);
}
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.