tags:

views:

100

answers:

4

Hello,

I am working on a project in C which requires me to read in matrix values from a txt file. The first two lines are the number of rows and columns, and the rest is the actual matrix data.

For example, something like this:

2
2
1.0 2.0
3.0 4.0

The code I wrote is giving me some issues. Here's a snippet:

matrix read(char* file){

 FILE *fp;
 printf("check 1\n");
 fp = fopen(file,"r");
 printf("file opened\n");

 // Make the new matrix
 matrix result;
 printf("matrix created\n");

 int counter = 0;
 int i;
 int j;
 int holdRows;
 int holdColumns;


 if(counter == 0)
 {          // read in rows
            fscanf(fp, "%li", holdRows);
            printf("here is holdRows: %li\n", holdRows);
            counter++;
 }
 if(counter == 1)
 {          // read in columns
            fscanf(fp, "%li", holdColumns);
            printf("here is holdColumns: %li\n", holdColumns);
            counter++;
            // Now that I know the dimensions, make the matrix
            result = newMatrix(holdRows, holdColumns);
 }
 // For the rest, read in the values
 for(i = 0; i < holdRows; i++)
       for(j = 0; j < holdColumns; j++)
             fscanf(fp, "%lf", &result->matrixData[i][j]);


 fclose(fp);
 return result;
}

Whenever I run this, holdRows and holdColumns are not the values stored in the txt file. For example, I tried a 3X4 matrix, and it read that there was one row and three columns.

Can anyone tell me what I'm doing wrong?

Thanks :)

A: 

You are not passing the address of holdRows and holdColumns to fscanf. You have to change them to fscanf(fp, "%li", &holdRows); and fscanf(fp, "%li", &holdColumns);.

dbarbosa
A: 

the %li conversion specification requires a long* as matching argument to fscanf(): you're passing a int (int* after correction proposed by dbarbosa).

Try "%i" ... and same for printf().


The %lf expects a double. Is matrix made of doubles?

pmg
Yes, matrix is made of doubles.
A: 

Try replacing:

 for(i = 0; i < holdRows; i++)
       for(j = 0; j < holdColumns; j++)
             fscanf(fp, "%lf", &result->matrixData[i][j]);

with

 double temp;
 for(i = 0; i < holdRows; i++)
       for(j = 0; j < holdColumns; j++) {
             fscanf(fp, "%lf", &temp);
             result->matrixData[i][j] = temp;
       }

I seem to recall that in C some types of 2D arrays don't play nice with &.

qdjm
That might work, but I'm not sure, since I'm still reading in incorrect values for holdRows and holdColumns, and holdColumns is in the 7 digits, so the loop goes on for a very long time.
@buzzbuzz: test the return value of `scanf` and exit the loop early if there's an error
pmg
+1  A: 

Thanks to suggestions by you all and some sleuth work myself, I solved my problem. First, I was entering the wrong filename (well, now I feel silly), and second, I was reading the data in as the wrong type.

Thanks, everyone, for your help!

You return a local variable, this function will never work.