简体   繁体   中英

Read matrix data and its dimensions from file [C++]

I have a txt file which is structured as follows:

<num Rows> <num Columns>
<M(0,0)> ... <M(0,nColumns-1)>
...
<M(nRows-1,0)> ... <M(nRows-1,nColumns-1)>

In other words the first line is just 2 scalars, namely the number of rows and columns in the matrix. From the second line, the matrix body starts.

I want to import such matrix in C++, following these steps:

  1. Preallocation of a matrix with nRows rows and nColumns columns after reading the first line
  2. Fill the matrix by reading the rest of the txt file.

I've been trying so far the following code:

har line[256];
int nRows; int nCols;
int i; int j;

bool FirstLine=true;
while (fgets(line, sizeof(line), fileIN)) {
    if (FirstLine==true){
        char nRowsC=line[0];
        nRows=nRowsC- '0';

        char nColsC=line[2];
        nCols=nColsC- '0';

        FirstLine=false;

        double **myMat=(double**)malloc(nRows*sizeof(double*));
        for(i=0; i<nRows; i++){
            myMat[i]=(double*)malloc(nCols*sizeof(double));
        }

        printf("Number of rows in data matrix: %d\n",nRows);
        printf("Number of columns in data matrix: %d\n\n",nCols);

        for(i = 0; i < nRows; i++)
        {
            for(j = 0; j < nCols; j++)
            {
                if (!fscanf(fileIN, "%lf", &myMat[i][j]))
                    break;
                printf("(%d,%d) %lf\n",i,j,myMat[i][j]);
            }

        }
    }
}
cout << '\n'; cout << '\n'; cout << '\n';
for(i = 0; i < nRows; i++)
{
    for(j = 0; j < nCols; j++)
    {
        printf("(%d,%d) %lf\n",i,j,myMat[i][j]); //<-- this line gives the error
    }
}

And everything seems ok but if I print out such matrix I get an error that identifier "myMat" is undeclared (in particular: "Use of undeclared identifier 'myMat'". Compiler: XCode 7.2 on Mac OS X 10.11).

You said it yourself: myMat is declared in... a scope that has already been closed.

Unlike Python, C++ has block-scoping rules:

double** myMat;
{
   int inner;
   myMat = foo(); // allowed: myMat is visible here
}
inner = 5; // compiler error: inner not visible anymore

If you want to access this variable, you should declare it in the outer scope, and fill it where you fill it now.

As a sidenote, C++ is evolving in a direction where we don't allocate much anymore in application code. Your code will probably be a lot safer and more readable if you revert it to use std::vector :

using Row = std::vector<double>;
using Matrix = std::vector<Row>;

Matrix myMat;

see an example at http://cpp.sh/4iu4 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM