如何将数字从文件输入到矩阵中

How do I enter numbers from a file into a matrix?

本文关键字:输入 文件 数字      更新时间:2023-10-16

由于某种原因,在从文件中输入值后,矩阵中每个数字的值都为零。当我用全零初始化矩阵时,它可以工作,但由于某种原因,我无法从文本文件中导入数字。

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

您没有显示任何设置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;
}