开发者

Need help reading from a txt file in C

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
         开发者_Python百科   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 :)


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 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);.


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?


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 &.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜