Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何从txt文件读取矩阵到模板矩阵?_C++_File Io - Fatal编程技术网

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

C++ 如何从txt文件读取矩阵到模板矩阵?,c++,file-io,C++,File Io,我有一个模板矩阵,我不知道如何读取我的“matrix1”txt文件。我需要如何定义“open1”方法?这是我的类和文件。 在文件中,前两个数字是矩阵的行和列 template <class T = double> class Matrix { private: unsigned row; unsigned column; T ** matrix; template<class

我有一个模板矩阵,我不知道如何读取我的“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();
     };
编辑:

这是我的新代码,但使用它我无法构建解决方案,我不知道如何处理错误:抛出异常:读取访问冲突。 该->矩阵为0x1110112。“

模板
布尔矩阵::open1()
{   
ifstream myfile(“matrix1.txt”);
如果(!myfile)
{
库特街;
myfile>>列;
对于(int i=0;i>矩阵[i][j];
}
}
myfile.close();
返回true;
}}将成为你的朋友:

与使用文件指针不同,您只需使用流:

ifstream ifs("matrix1.txt");     // istream is "r"
您可以检查流是否有问题

if (!ifs) {
    // .. ouch 
}
读取数据非常简单

ifs >> row >> column; 

C++推断出要读取的数据类型,因此不需要使用
scanf()
中所需的易于出错的
%d“
%lf”

此外,它的功能更强大,因为如果您将矩阵实例化为
T
而不是
double
,它将始终调用流提取器的正确重载。例如,对于
matrix
,您可以使用相同的模板代码读取如下文件:

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

将是您的朋友:

与使用文件指针不同,您只需使用流:

ifstream ifs("matrix1.txt");     // istream is "r"
您可以检查流是否有问题

if (!ifs) {
    // .. ouch 
}
读取数据非常简单

ifs >> row >> column; 

C++推断出要读取的数据类型,因此不需要使用
scanf()
中所需的易于出错的
%d“
%lf”

此外,它的功能更强大,因为如果您将矩阵实例化为
T
而不是
double
,它将始终调用流提取器的正确重载。例如,对于
matrix
,您可以使用相同的模板代码读取如下文件:

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

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

你试了什么?我写它作为答案-如果你想对你的问题进行补充,请编辑你的问题。答案用于答案。这是我的文件-不同行中的数字应该是什么意思?矩阵的元素
Matrix M;
open1
函数无关。将其删除,并将该函数中的所有
M.anything
替换为
anything
。您尝试了什么?我将其作为答案写下–如果您想对问题进行补充,请编辑您的问题。答案用于答案。这是我的文件–号码是什么s在不同的行中应该是什么意思?矩阵的元素
matrix M;
open1
函数中没有任何意义。删除它并将所有
M.anything
替换为
anything
@jacky太好了!如果它解决了问题并且有帮助,别忘了接受答案;-)但是要构建ld我还想知道如何处理异常:/@jacky很棒!如果它解决了问题并且有帮助,请不要忘记接受答案;-)但对于构建,我还想知道如何处理异常:/