title: How to read CSV file and assign to Eigen Matrix?
body: <p>I try to read a large cvs file into Eigen Matrix, below the code found having problem where it can not detect each line of \n in cvs file to create multiple rows in the matrix. (It read entire file with single row). Not sure what's wrong with the code. Can anyone suggest here?
  Im also looking for a effective way to read csv file with 10k of rows and 1k of cols. Not so sure the code below will be the best effective way? Very appreciated with your comment.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;istream&gt; //DataFile.fail()  function
  #include &lt;vector&gt;
  #include &lt;set&gt;
  #include &lt;string&gt;
  using namespace std;
  
  
  #include &lt;Eigen/Core&gt;
  #include &lt;Eigen/Dense&gt;
  using namespace Eigen;
  
   void readCSV(istream &amp;input, vector&lt; vector&lt;string&gt; &gt; &amp;output)
  {
      int a = 0;
      int b = 0;
  
      string csvLine;
      // read every line from the stream
      while( std::getline(input, csvLine) )
      {
  
          istringstream csvStream(csvLine);
          vector&lt;string&gt; 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 &lt;&lt; "a : " &lt;&lt; a &lt;&lt; " b : " &lt;&lt; b &lt;&lt; endl;   //a doen't detect '\n'
  }
  
  int main(int argc, char* argv[])
  {
  
      cout&lt;&lt; "ELM" &lt;&lt; endl;
      //Testing to load dataset from file.
      fstream file("Sample3.csv", ios::in);
      if(!file.is_open())
      {
          cout &lt;&lt; "File not found!\n";
          return 1;
      }
      MatrixXd m(3,1000);
      // typedef to save typing for the following object
      typedef vector&lt; vector&lt;string&gt; &gt; 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&lt;string&gt;::iterator j = i-&gt;begin(); j != i-&gt;end(); ++j)
          {
             m(i,j) = *j; 
             cout &lt;&lt; *j &lt;&lt; ", ";
          }
          cout &lt;&lt; "\n";
      }
  }
  </code></pre>
  
  <p>I will also attach a sample cvs file. <a href="https://onedrive.live.com/redir?resid=F1507EBE7BF1C5B!117&amp;authkey=!AMzCnpBqxUyF1BA&amp;ithint=file%2ccsv" rel="nofollow">https://onedrive.live.com/redir?resid=F1507EBE7BF1C5B!117&amp;authkey=!AMzCnpBqxUyF1BA&amp;ithint=file%2ccsv</a></p>