簡體   English   中英

從文件[C ++]中讀取矩陣數據及其維數

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

我有一個txt文件,其結構如下:

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

換句話說,第一行只有2個標量,即矩陣中的行數和列數。 從第二行開始,矩陣主體。

我想按照以下步驟在C ++中導入這樣的矩陣:

  1. 讀取第一行后,預先分配nRows行和nColumns列的矩陣
  2. 通過閱讀txt文件的其余部分來填充矩陣。

到目前為止,我一直在嘗試以下代碼:

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
    }
}

一切似乎都很好,但是如果我打印出這樣的矩陣,則會收到未聲明標識符“ myMat”的錯誤(特別是:“使用未聲明的標識符'myMat'”。編譯器:在Mac OS X 10.11上為XCode 7.2)。

您自己說過: myMat在...一個已經關閉的范圍中聲明。

與Python不同, C ++具有塊作用域規則:

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

如果要訪問此變量,則應在外部范圍中聲明它,並在現在填充它的位置填充它。

附帶說明,C ++朝着我們不再在應用程序代碼中分配太多的方向發展。 如果將其還原為使用std::vector則代碼可能會更安全,更易讀:

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

Matrix myMat;

請參閱http://cpp.sh/4iu4上的示例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM