请帮我多维向量。 我有一个csv文件。我想要的是它会:
即使是简单的示例代码也可以。
我最终得到了这个,但我卡住了。
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;
}
答案 0 :(得分:2)
尝试将while循环更改为以下内容:
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);
}
答案 1 :(得分:0)
你非常接近。尝试以下几点修改:
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;
}