从文件中读取多维向量

时间:2015-04-23 10:24:24

标签: c++ file vector dimensions

我需要将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;
      }
}

矩阵显示所有行,但它们都与第一行重复。出于某种原因,只读了第一行。

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

在重复使用之前,您必须清除aRow。否则,你不断将相同的值推入矩阵。

aPipes.push_back(aRow);添加aRow.clear();

之后