2016-08-18 6 views
0

なんらかの理由で、ファイルから値を入力した後、行列内のすべての数値の値がゼロになります。それは私がすべてのゼロで行列を初期化するときに機能しましたが、何らかの理由でテキストファイルからインポートする数値を取得できません。ファイルから行列に数値を入力するにはどうすればよいですか?

struct Vector { 
    float* els; 
    int len; 
    }; 

struct Matrix { 
    Vector* col; // col is array of Vectors; each Vector is one column of matrix 
    int ncols; // total number of columns in matrix 
}; 

...

ifstream fin("mat.def"); 
fin >> m >> n; 
fin >> M; 

...

istream& operator>>(istream& input, Matrix& mm) { 

int m,n; 
    n=mm.ncols; 

    mm.col = new Vector[n]; // use n instead m for consistency 

    for (int i=0;i<n;i++) { 
    mm.col[i].els = new float[m]; 
    for (int k=0;k<m;k++) { 
     input >> mm.col[i].els[k]; 
    } 
    } 

    return input; 
} 

答えて

0

あなたはnm.ncolsの値を設定し、任意のコードを示していません。私の推測では、nm.colsの値が使用される前に正しく設定されていないということです。

戦略を少し変更することをおすすめします。代わりに

fin >> m >> n; 
fin >> M; 

の使用

fin >> M; 

と列数と行数がoperator>>機能に読まれていることを確認します。

std::istream& operator>>(std::istream& input, Matrix& mm) 
{ 
    int rows; 
    input >> mm.ncols; 
    input >> rows; 

    mm.col = new Vector[mm.ncols]; 

    for (int i=0;i<mm.ncols;i++) 
    { 
     mm.col[i].len = rows; 
     mm.col[i].els = new float[rows]; 
     for (int k=0;k<rows;k++) { 
     input >> mm.col[i].els[k]; 
     } 
    } 

    return input; 
} 
関連する問題