如何将数字从文件输入到矩阵中
How do I enter numbers from a file into a matrix?
由于某种原因,在从文件中输入值后,矩阵中每个数字的值都为零。当我用全零初始化矩阵时,它可以工作,但由于某种原因,我无法从文本文件中导入数字。
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;
}
相关文章:
- 用c++从输入文件中读取另一行
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 获取通过重定向传入的输入文件的名称?
- C++ 如何打开带有另一个目录的输入文件?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 如何从输入文件 c++ 创建随机名称生成器
- 从输入文件修剪空格
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 我遇到使用 c++ 逐行读取输入文件的问题
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 使用 getline 从输入文件打印时如何忽略空白行
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 数组大小由输入文件中的行数定义
- 从C++输入文件读取
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 利用输入文件中的数据(字符串和int)并在循环中利用
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- 如何从输入文件中读取字符并将其存储到向量中?