我在读取文件内容方面没有问题,但我希望以数组格式存储这些值。我该怎么做 ?
档案内容:
1,2,4,4,0,30,15,7.6,5
1,2,4,5,0,0,0,0,0
1,3,2,1,0,40,29,14,9.6
1,3,2,2,0,0,19,9.4,6.2
代码:
ifstream infile;
infile.open ("test.txt");
if (infile.is_open())
{
while (infile.good())
{
cout << (char) infile.get();
}
infile.close();
}
else
{
cout << "Error opening file";
}
return 0;
答案 0 :(得分:1)
void parser()
{
ifstream data("test.txt");
string line;
vector<vector<string>> parsedRow;
while(getline(data,line))
{
stringstream lineStream(line);
string cell;
vector<string> parsedRow;
while(getline(lineStream, cell, ','))
{
parsedRow.push_back(cell);
}
parsedCsv.push_back(parsedRow);
}
};
如果你想要浮点数组,
void parser()
{
ifstream data("test.txt");
string line;
vector<vector<float>> parsedRow;
while(getline(data,line))
{
stringstream lineStream(line);
string cell;
vector<float> parsedRow;
while(getline(lineStream, cell, ','))
{
float f_cell = atof(cell.c_str());
parsedRow.push_back(f_cell);
}
parsedCsv.push_back(parsedRow);
}
};