【问题标题】:How to read a matrix from txt file to template matrix?如何从 txt 文件中读取矩阵到模板矩阵?
【发布时间】:2019-05-04 08:09:43
【问题描述】:

我有一个模板矩阵,但我不知道如何阅读我的“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

编辑:

这是我的新代码,但我无法构建解决方案,也不知道如何处理错误:抛出异常:读取访问冲突。 this->矩阵是 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;

}}

【问题讨论】:

  • 你尝试了什么?
  • 我把它写成答案 – 如果你想对你的问题进行补充,请编辑你的问题。答案是为了答案。
  • 这是我的文件——不同行中的数字应该是什么意思?
  • 矩阵的元素
  • Matrix&lt;T&gt; M;open1 功能无关。删除它并将该函数中的 allM.anything 替换为 anything

标签: c++ file-io


【解决方案1】:

&lt;fstream&gt; 将成为你的朋友:

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

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

可以检查流是否有问题

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

读取数据就这么简单

ifs >> row >> column; 

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

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

此外,它更强大,因为如果您使用T 而不是double 来实例化矩阵,它总是会调用流提取器的正确重载。例如,使用Matrix&lt;std::complex&lt;double&gt;&gt;,您可以使用相同的模板代码读取如下文件:

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

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

【讨论】:

  • @jacky 太棒了!如果它解决了问题并且有帮助,请不要忘记接受答案 ;-)
  • 但是要构建我也想知道如何处理异常:/
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 2019-08-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-30
相关资源
最近更新 更多