Reputation: 15
Please help me with multidimensional vectors. I have a csv file. what I want is that it will:
Even a simple sample code will do.
I ended up with this, but I got stuck.
vector< vector <string> > THIRDSTEP::DispSched(string movies)
{
ifstream file("sched1.csv");
vector < vector<string> > data(7, vector<string>(6));
while (!file.eof())
{
for (int r = 0; r < 7; ++r)
{
vector<string> row;
string line;
getline(file, line);
if (!file.good())
break;
stringstream iss(line);
for (int c = 0; c < 7; ++c)
{
string val;
getline(iss, val, ',');
if (!iss.good())
break;
stringstream convert(val);
data.push_back(convert);
}
}
}
return data;
}
Upvotes: 1
Views: 3728
Reputation: 193
You're very close. Try these few modifications:
vector< vector <string> > THIRDSTEP::DispSched(string movies)
{
ifstream file("sched1.csv");
vector < vector<string> > data(7, vector<string>(6));
// Clear the array since the rows will be initialized with empty string vectors
data.clear();
while (!file.eof())
{
for (int r = 0; r < 7; ++r)
{
vector<string> row;
string line;
getline(file, line);
if (!file.good())
break;
stringstream iss(line);
for (int c = 0; c < 7; ++c)
{
string val;
getline(iss, val, ',');
if (!iss.good())
break;
// Not needed, since you only need the one value
//stringstream convert(val);
row.push_back(val);
}
// Since you've built the columns, add the row
data.push_back(row);
}
}
return data;
}
Upvotes: 0
Reputation: 12715
Try changing your while loop to something like the following.:
string line;
int r = 0;
// We can build the vector dynamically. No need to specify the length here.
vector < vector<string> > data;
// while r < 7 and getline gives correct result
while (r < 7 && getline(file, line))
{
vector<string> row;
stringstream iss(line);
int c = 0;
string val;
// while c < 7 and getline gives correct result
while (c < 7 && getline(iss, val, ','))
{
// no need for converting as you are reading string.
row.push_back(val);
}
data.push_back(row);
}
Upvotes: 3