矩阵中的读取访问冲突

时间:2019-05-11 21:04:52

标签: c++ fstream

在尝试构建解决方案时遇到读取访问冲突。我有一个矩阵类,我想从txt文件中读取一个矩阵(可以使用)。通过调试没有错误,但是当我尝试运行时该程序我收到了“异常抛出消息”。消息在open1方法中出现在“矩阵[i] [j]”-s行中。

{
template <class T>
bool Matrix<T> ::open1()


{


    ifstream myfile("matrix1.txt");

    if (!myfile)
    {
        cout << "Error in file opening" << endl;

        return false;

    }
    myfile >> row;
    myfile >> column;
    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < column; i++)
        {
            myfile >> matrix[i][j];
        }
    }




    myfile.close();                     
    return true;
}

这是班上

{
template<class T = double>
class Matrix
{
private:
unsigned row;
unsigned column;
T **matrix;
template<class OUTP>
friend std::ostream& operator<<(std::ostream&, const Matrix<OUTP>&);
template<class INP>
friend std::istream& operator>>(std::istream&, Matrix<INP>&);
public:
Matrix(unsigned = 0, unsigned = 0);
~Matrix();
Matrix(const Matrix<T>&);
void setMatrixElment(unsigned, unsigned, T);
void delMatrix();
unsigned getRow()const { return row; }
unsigned getColumn()const { return column; }
T getElement(unsigned = 0, unsigned = 0);
Matrix<T>& operator=(const Matrix<T>&);
Matrix<T> operator+(const Matrix<T>&);
Matrix<T> operator-(const Matrix<T>&);

Matrix <T>inverz();
bool open1();
bool open2();

Matrix<T> operator*(const double&);
Matrix<T> operator*(const Matrix<T>&);
T determinant() const;
};

}

我的txt文件是这个

{
  3 3
26.062000 16.600000 24.900000 
49.800000 0.000000 1.000000 
2.000000 4.000000 5.000000

如果我分配内存,它仍然不会读取元素。(我很好地定义了复杂的类,使用类型没有问题)     {

template <class T>
bool Matrix<T> ::open1()


{


    ifstream myfile("matrix1.txt");

    if (!myfile)
    {
        cout << "Error in file opening" << endl;

        return false;

    }

    Matrix<Complex> b;
    myfile >> b.row;
    myfile >> b.column;
    b.matrix = new T*[b.row];  
    for (unsigned i = 0; i < b.row; i++)
    {
        b.matrix[i] = new T[b.column];
    }
    for (int j = 0; j < b.row; j++)
    {
        for (int k = 0; k< b.column; k++)
        {
            myfile >> b.matrix[j][k];
        }
    }




    myfile.close();                     
    return true;
}
}

1 个答案:

答案 0 :(得分:1)

我相信您不会在任何地方为matrix 分配内存,因为当您读取矩阵的尺寸(rowcolumn)中,您急忙分析文件中矩阵的值。

您需要根据情况动态分配内存,如下所示:

myfile >> row;
myfile >> column;

matrix = new T*[row];
for(int i = 0; i < row; ++i)
    matrix[i] = new T[column];

for (int i = 0; i < row; i++)
{
    for (int j = 0; j < column; i++)
    {
        myfile >> matrix[i][j];
    }
}