Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Read CSV file, Vector<Vector

$
0
0
I have to read the following CSVdata into vector of vectors

Anna
2,4, 4
xx, xx, xx, xx
100


I have the following function to red the data in


Header

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <algorithm>


std::vector<std::vector<std::string> > readCSV1(std::fstream& inn)
{
   
   std::vector<vector<std::string> > contents;
    std::string s;
    size_t lastpos, curpos;

    while(std::getline(inn, s))
    {
   contents.push_back( vector<std::string>());
    for (lastpos=curpos=0; curpos!=std::string::npos; lastpos=curpos+1)
    {
      curpos = s.find(',', lastpos);
      if (curpos != std::string::npos)
        contents.back().push_back(s.substr(lastpos, curpos-lastpos));
      else
        contents.back().push_back(s.substr(lastpos));
    }
    }
    return contents;
} 


int main()
    // read the file
  string Filename7;          
  cout << "Give name of input file Data.csv: ";
cin >> Filename7;
     std::fstream dataFile7(Filename7.c_str());
    std::vector<std::vector<std::string> > csv;
    csv= readCSV1(dataFile7);
for (size_t i=0; i < csv.size(); i++)
  {
    for (size_t j=0; j < csv[i].size(); j++)
    {
        cout << csv[i][j] << "\t";
    }
    std::cout << endl;
  }
    cout<<csv[0][0]<<endl;
        
     }



I do not really get the output in the matrix form, the lines are not parsed into strings.
The size of my vector is [7][0], instead of [2][3] How should I modify the code to parse the strings in the lines into vectors?

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>