Hi all,
I am struggling
in reading a file.csv onto c++, and hope experienced users of c++ could assist:
ISN,Date,Open,High,Low,Close,Volume,Adj Close
US128745,20140602,20.62,20.82,20.43,20.52,501500,20.52
FR5679,20140501,19.53,20.6,19.01,20.48,92000,20.48
XS23457,20140401,18.56,19.52,18.28,19.48,77100,18.16
ES6754,20140303,17.49,18.59,17.2,18.5,124800,18.16
Main concern:
1- the output ignores string, thus 0 values are assigned to string characters;
0 0 0 0 0 0 0 0
0 20140602 20.62 20.82 20.43 20.52 501500 20.52
...
if *line_contents.push_back( 0 )* is commented in the code as a solution to the assigned 0 values, then string characters are unfortunately skipped from the output
2- Inability to reference any single column vector (n X 1), without creating duplicated values and keeping the file dimension (n X p);
e.g std::cout << csv[i][1] << "\t";
below is the blocks of code used:
#include <iostream>
#include <sstream>
#include <fstream>
#include <vector>
#include <string>
#include <algorithm>
std::vector<std::vector<int> > readCSV(std::string filename)
{
std::vector<std::vector<int> > contents;
std::ifstream in(filename);
std::string line;
while(getline(in, line))
{
contents.push_back( std::vector<int>());
std::vector<int>& line_contents = contents[contents.size()-1];
std::istringstream iss(line);
do
{
int value;
if( iss >> value )
{
line_contents.push_back(value);
}
else
{
line_contents.push_back( 0 );
iss.clear();
}
std::string fieldend;
getline(iss, fieldend, ',');
}
while(!iss.eof());
}
return contents;
}
int main() {
std::vector<std::vector<int> > csv = readCSV("DATA.csv");
for(size_t i=0; i<csv.size(); ++i) {
for(size_t j=0; j<csv[i].size(); ++j){
std::cout << csv[i][j] << "\t";
}
std::cout<<std::endl;
system("pause");
Thanks & regards