0
我需要將txt文件中的值讀入n x 20向量。該文件就是這樣從文件中讀取多維向量
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
我想出的代碼如下
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;
然而,當我打印整個向量像這樣,
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;
}
}
矩陣顯示所有但它們都是第一個的重複。出於某種原因,只有第一行被讀取。
任何幫助,將不勝感激。
因爲你需要一個循環讀取文件的所有行。你解決問題的方式並不好。你應該寫一個函數,將一行轉換成一個向量,並調用文件中每一行的這個函數。 – alifirat
'aPipes.push_back(aRow);'add'aRow.clear();' – WaeCo