如何从txt文件读取矩阵到模板矩阵?

时间:2019-05-04 08:09:43

标签: c++ file-io

我有一个模板矩阵,但我不知道如何读取我的“ matrix1” txt文件。如何定义“ open1”方法?这是我的课程和我的文件。 在文件中,前两个数字是矩阵的行和列。

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 & other);
         void setMatrixElement(unsigned, unsigned, T);
         void delMatrix();
         T getElement(unsigned = 0, unsigned = 0);
         unsigned getRow()const { return row; }
         unsigned getColumn()const { return column; }

         bool open1();
     };

这是我的文件

 3 3
26.062000 16.600000 24.900000 49.800000 0.000000 1.000000 2.000000 
4.000000 5.000000

编辑:

这是我的新代码,但与此有关,我无法构建解决方案,而且我不知道如何处理错误:抛出异常:读取访问冲突。 此->矩阵为0x1110112。”

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


{   
ifstream myfile("matrix1.txt");

if (!myfile)
{
    cout << "Error with fileopening" << 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;

}}

1 个答案:

答案 0 :(得分:0)

<fstream>将成为您的朋友:

您无需使用文件指针,而只需使用流:

ifstream ifs("matrix1.txt");     // istream is "r"

您可以检查流是否有问题

if (!ifs) {
    // .. ouch 
}

读取数据就像

ifs >> row >> column; 

ifs >> M.matrix[j][g]; 

C ++会推断您要读取的数据类型,因此您无需使用"%d"中所需的容易发生手动错误的"%lf"scanf()

此外,它的功能要强大得多,因为如果使用T而非double实例化矩阵,它将始终调用流提取器的正确重载。例如,使用Matrix<std::complex<double>>,您可以使用相同的模板代码读取文件,例如:

2 2
(1.0,1.0) 2.0  
(2.5,4) (2.0,1.0) 

其中(2.0,1.0)是一个复数的标准表示,其中2.0为实部,而1.0为虚部。

相关问题