使用Eigen库时如何读取文件?

时间:2018-01-26 11:36:25

标签: c++ file eigen3

我尝试使用fscanf()读取文本文件但是当我使用Eigen库时它不起作用。所以我包含了iterator和fstream头文件来读取文本文件并查找行和列。

#include <iostream>
#include<math.h>
#include<complex.h>
#include<vector>
#include<algorithm>
#include<iterator>
#include<fstream>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Core>
#include<math.h>
using namespace Eigen;
using namespace std;
using Eigen::MatrixXf;

void ReadFromTextFile(Eigen ::MatrixXf, const char*);   

int main()
{
    MatrixXf x;
    ReadFromTextFile(x,"data.txt");
    cout << "Rows: " << x.rows() << "Cols: " << x.cols() << endl;
}

void ReadFromTextFile(Eigen ::MatrixXf &matrix ,const char *filename)
{
    std::ifstream inFile (filename,std::ios::in);
         if(!inFile.good())
          { std::cout<<"Error: could not open file:\""<<filename<<"\"for reading \n";
            exit (2);
           }
        //find the no of values in file
        std::istream_iterator<std::string> in{inFile};
        std::istream_iterator<std::string> end;
        long numberofWords=std::distance(in,end);
        //find the no of lines in file
        inFile.clear();
        inFile.seekg(0,std::ios::beg);
        long numberofLines=std::count(std::istreambuf_iterator<char>(inFile),std::istreambuf_iterator<char>(),'\n');
         std::cout<<"no. of words : "<<numberofWords<<"numberofLines: "<<numberofLines<<std::endl;
        long rows=numberofLines;
        long cols=numberofWords/numberofLines;
        if(rows*cols!=numberofWords)
          { std::cout<<"\n Infile"<<filename<<"cannot form a matrix \n";
            exit(2);
          }
        matrix.array().resize(rows,cols);
        //matrix Base does not allow resizing ...hence change array base
        inFile.clear();
        inFile.seekg(0,std::ios::beg);
        for(unsigned int i=0;i<matrix.rows();i++)
         for(unsigned int j=0;j<matrix.cols();j++)
           inFile>>matrix(i,j);
        inFile.close();


        }

但是当我编译我的代码时,我得到了

hp@hp-HP-Notebook:~/beamforming/programs/eigen_prog/subprogram_try$ g++ file.cpp -o file -lm -std=c++11
/tmp/cc57aQIl.o: In function 'main':file.cpp:(.text+0x48): undefined reference to `ReadFromTextFile(Eigen::Matrix<float, -1, -1, 0, -1, -1>, char const*)' collect2: error: ld returned 1 exit status

我无法弄清楚代码中的错误。请帮忙

1 个答案:

答案 0 :(得分:0)

您的声明:

void ReadFromTextFile(Eigen ::MatrixXf  ,const char*);   

与您的定义不符:

void ReadFromTextFile(Eigen ::MatrixXf &matrix ,const char *filename)