I need to read values from a txt file into a n x 20 vector. The file is like that
pipe 1 2 0 1 1 50 120 5 5 6 0 0
pipe 2 3 0 1 1 50 120 4 5 2 0 0
pipe 3 4 0 1 1 25 120 1 5 4 80 90
The code I came up with is as follows
vector<double> aRow;
vector< vector < double >> aPipes;
ifstream inf("F:\\text.txt");
while (inf >> c0 >> c1 >> c2 >> c3 >> c4 >> c5 >> c6 >> c7 >> c8 >> c9 >> c10 >> c11 >> c12)
{
if (c0 == "pipe")
{
aRow.push_back(c1);
aRow.push_back(c2);
aRow.push_back(0);
aRow.push_back(c4);
aRow.push_back(c5);
aRow.push_back(c6);
aRow.push_back(c7);
aRow.push_back(c8);
aRow.push_back(c9);
aRow.push_back(c10);
aRow.push_back(c11);
aRow.push_back(c12);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aRow.push_back(0);
aPipes.push_back(aRow);
i++;
}
}
nNumPipes = i;
cout << "Num of pipes: " << nNumPipes << endl;
However when I print the entire vector such as this,
for (int i = 0; i < nNumPipes; i++)
{
{for (int j = 0; j < 20; j++)
cout << setprecision(3) << aPipes.at(i).at(j) << "\t";
cout << endl;
}
}
the matrix shows all lines but they are all duplicate of the first. For some reason only the first line is read.
Any help would be appreciated.
You have to clear aRow
before reusing it. Otherwise you keep pushing the same values into your matrix.
After aPipes.push_back(aRow);
add aRow.clear();