我尝试将一个大的CVS文件读入Eigen Matrix,在发现有问题的代码下面,它无法检测到CVS文件中的每行\ n以在矩阵中创建多行。 (它用单行读取整个文件)。不知道代码有什么问题。任何人都可以在此建议 林也寻找一种有效的方式来读取10k行和1k cols的csv文件。不太确定下面的代码是否是最有效的方式?非常感谢您的评论。如何读取CSV文件并将其分配给特征矩阵?
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <fstream>
#include <istream> //DataFile.fail() function
#include <vector>
#include <set>
#include <string>
using namespace std;
#include <Eigen/Core>
#include <Eigen/Dense>
using namespace Eigen;
void readCSV(istream &input, vector< vector<string> > &output)
{
int a = 0;
int b = 0;
string csvLine;
// read every line from the stream
while(std::getline(input, csvLine))
{
istringstream csvStream(csvLine);
vector<string> csvColumn;
MatrixXd mv;
string csvElement;
// read every element from the line that is seperated by commas
// and put it into the vector or strings
while(getline(csvStream, csvElement, ' '))
{
csvColumn.push_back(csvElement);
//mv.push_back(csvElement);
b++;
}
output.push_back(csvColumn);
a++;
}
cout << "a : " << a << " b : " << b << endl; //a doen't detect '\n'
}
int main(int argc, char* argv[])
{
cout<< "ELM" << endl;
//Testing to load dataset from file.
fstream file("Sample3.csv", ios::in);
if(!file.is_open())
{
cout << "File not found!\n";
return 1;
}
MatrixXd m(3,1000);
// typedef to save typing for the following object
typedef vector< vector<string> > csvVector;
csvVector csvData;
readCSV(file, csvData);
// print out read data to prove reading worked
for(csvVector::iterator i = csvData.begin(); i != csvData.end(); ++i)
{
for(vector<string>::iterator j = i->begin(); j != i->end(); ++j)
{
m(i,j) = *j;
cout << *j << ", ";
}
cout << "\n";
}
}
我也将附上一个示例CVS文件。 https://onedrive.live.com/redir?resid=F1507EBE7BF1C5B!117&authkey=!AMzCnpBqxUyF1BA&ithint=file%2ccsv
截至目前您的分隔符是空的:'”“'。你的意思是:'','? –
嗨卢卡斯,是的,我确实在我的第一个代码尝试',',但因为它不检测我的CVS文件中每行的行尾,所以我试着让它''..但它似乎仍然失败。 –
'm(i,j)= * j;'这是不正确的。 – 5gon12eder