I am trying to add CSV file into a 2D array vector ie: vector of vector. The following program works well but there is a small problem,
For example to add the 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 the 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 the data line by 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 a new inner vector
vec.push_back(std::vector<float>());
}
vec[col].push_back(value);
++col;
// read past the separator
split>>sep;
}
// Finished reading line 1 and creating as many inner
// vectors as required
first = true;
}
However, The above code executes and adds data into the vector, but rather than adding each value in the first line in inner vector it adds the column as a row in the inner vector. I mean to say the rows and column in the CSV file becomes column and rows in the vector respectively. If I do a cout then I get the 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. the row and column is reversed, How do I turn things around.
Thank you for looking at this probelm.
Just add each row into a vector, and then push it back, instead of adding to each vector each time:
while (getline(file,line)) //reading the data line by line
{
std::vector<float> nextRow;
// etc.
while (split >> value)
{
nextRow.push_back(value);
split >> sep;
}
vec.push_back(nextRow);
}
void Table::addTableData(string filename)
{ vector > vec;
ifstream file(filename.c_str());
bool first = false;
if (file)
{
string line;
int col = 0;
while (getline(file,line)) //reading the data line by line
{
istringstream split(line);
float value;
char sep;
vec.push_back(std::vector<float>());
while (split >> value) //
{
/*
if(!first)
{
// Each new value read on line 1 should create a new inner vector
vec.push_back(std::vector<float>());
}
*/
vec[col].push_back(value);
/* ++col; */
// read past the separator
split>>sep;
}
// Finished reading line 1 and creating as many inner
// vectors as required
/* first = true; */
++col;
}
}
}
this code may work well
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.