c++11 - vector adds CSV column data into vector rows while transfering CSV file's data into c++ vector -
i trying add csv file 2d array vector i.e: vector of vector. following program works there small problem,
for example add following csv data:
1.4,23.44,24.4,3.0 2.3,4.3,44.5,6.6 3.4,33.2,5.4,3.65
i have used following code:
void table::addtabledata(string filename) vector<vector<float> > vec; ifstream file(filename.c_str()); bool first = false; if (file) { string line; while (getline(file,line)) //reading data line line { istringstream split(line); float value; int col = 0; char sep; while (split >> value) // { if(!first) { // each new value read on line 1 should create new inner vector vec.push_back(std::vector<float>()); } vec[col].push_back(value); ++col; // read past separator split>>sep; } // finished reading line 1 , creating many inner // vectors required first = true; }
however, above code executes , adds data vector, rather adding each value in first line in inner vector adds column row in inner vector. mean rows , column in csv file becomes column , rows in vector respectively. if cout following result
1.4 2.3 3.4 23.44 4.3 33.2 24.4 44.5 5.4 3.0 6.6 3.65
therefore. row , column reversed, how turn things around.
thank looking @ probelm.
just add each row vector, , push back, instead of adding each vector each time:
while (getline(file,line)) //reading data line line { std::vector<float> nextrow; // etc. while (split >> value) { nextrow.push_back(value); split >> sep; } vec.push_back(nextrow); }
Comments
Post a Comment