如何将值从文件输入到矩阵中
How do I input values from a file into a matrix?
我想使用函数将特定的值输入到矩阵中,但由于matInit函数中的一些错误,我一直收到分割错误。无论是否将其设置为bar.col[I],都会收到此错误。els[k]=0(如下所示)或者save bar。Col [i]作为一个数组,用k值做一个for循环。我感觉分割错误是由于尺寸不匹配,但我不知道我做错了什么。我还必须通过结构输入值,因为这是这个项目的要求。
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
struct Vector {
float* els;
int len;
};
struct Matrix {
Vector* col;
int ncols; // total number of columns in matrix
};
// Initializer functions for our structures
Vector vecInit(int); // Provided below
Matrix matInit(int,int); // ** You must complete this
// Overloaded operators
Vector operator+(Vector,Vector); // Provided below
Vector operator*(float,Vector); // ** You must write this
Vector operator*(Matrix,Vector); // ** You must write this
istream& operator>>(istream&, Vector&); // Provided below
istream& operator>>(istream&, Matrix&); // ** You must write this
// Other Vector functions
float vecDot(Vector,Vector); // ** You must write this
// main code
// **** This must be left unchanged in your submission *****
int main(void) {
int m,n,nv,nw;
ifstream fin("mat.def");
if (!fin.is_open()) {
cout << "Cannot find file mat.def!" << endl;
}
else {
// Load details of matrix M from file
fin >> m >> n;
Matrix M = matInit(m,n);
fin >> M;
cout << "M is " << m << "x" << n << endl;
}
return 0;
}
// *****************************************************
// Support function definitions
// ** Provided Code. Do not change **
// Vector structure initializer
// *** Partially provided code. Change as needed below ***
// Matrix structure initializer
Matrix matInit(int m, int n) {
Matrix bar;
bar.ncols = n;
bar.col = new Vector[m];
for (int i=0;i<n;i++) {
for (int k=0;k<m;k++) {
bar.col[i].els[k]=0;
}
}
return bar;
}
istream& operator>>(istream& input, Matrix& M) {
int leng=M.col[0].len;
for (int i=0;i<M.ncols;i++) {
for (int k=0;k<leng;k++) {
input >> M.col[i].els[k];
}
}
return input;
}
在为每个vector的元素赋值之前,必须先为其分配数组。
Matrix matInit(int m, int n) {
Matrix bar;
bar.ncols = n;
bar.col = new Vector[n]; // use n instead m for consistency
for (int i=0;i<n;i++) {
bar.col[i].els = new float[m]; // add this line to allocate arrays
for (int k=0;k<m;k++) {
bar.col[i].els[k]=0;
}
}
return bar;
}
相关文章:
- 用c++从输入文件中读取另一行
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- 获取通过重定向传入的输入文件的名称?
- C++ 如何打开带有另一个目录的输入文件?
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 如何从输入文件 c++ 创建随机名称生成器
- 从输入文件修剪空格
- 链接器输入文件未使用,因为链接未完成,我无法获得.o
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 我遇到使用 c++ 逐行读取输入文件的问题
- 使用重定向命令从 stdin 读入的字符串"<"输入文件未正确附加
- 使用 getline 从输入文件打印时如何忽略空白行
- 如何按升序对输入文件中的数字进行排序,并找到它们的范围和中值
- 数组大小由输入文件中的行数定义
- 从C++输入文件读取
- 在课堂上创建了一个朋友,给出"无输入文件"错误
- 通过显示一行星号来创建条形图,该条形图将读取数据的输入文件
- 利用输入文件中的数据(字符串和int)并在循环中利用
- C++ 仅读取输入文件中的部分(不是全部)数据以添加到记录中
- 如何从输入文件中读取字符并将其存储到向量中?