Here is something that I have been using, just read everything in with the first function and use the second function to separate the data by column.
LINE is a global typedef of vector<string> used to store each line of a CSV file, so the very first line will hold the column titles, which is used by the second function to separate the columns.
Code:
// Reads the datafile into vector stats
vector<LINE> readFile(const char *filename)
{
string line;
int pos;
ifstream fin(filename);
if(!fin.is_open())
{
cout << "Failed to open file" << endl;
system("EXIT");
}
while(getline(fin,line))
{
LINE ln;
while( (pos = line.find(',')) >= 0)
{
string field(line.substr(0,pos));
line = line.substr(pos+1);
ln.push_back(field);
}
stats.push_back(ln);
}
return stats;
}
// Parses the vector into rows of information by column and returns the row
string GetColData(int row_number, string ColName)
{
LINE &columnNames = stats[0];
// find the column with the above column name
for(int column = 0; column < columnNames.size(); column++)
{
if( ColName == columnNames[column] )
{
// get data for this column
LINE &row = stats[row_number];
return row[column];
}
}
return "";
}
I almost forgot, stats is also global, but this was just a temporary fix, in the final prog it is not global:
Code:
vector<LINE> stats;