c++如何从文本文件中的表中生成多维向量

c++ How to make multidimentional vector from a table in a text file?

本文关键字:向量 文本 文件 c++      更新时间:2023-10-16

我想将下表存储到c++中的多维向量中,这样我就可以通过列名调用值。这是我的桌子:

  1 #kjflsj sjflskjf
  2 100.00 200.43
  3 101.23 198.56
  4 102.12 201.87
  5 99.67 198.28
  6 #sfjslkdjf lsfjls jf jslkfjsij osiioj o
  7 100.54 205.98
  8 99.87 199.34
  9 101.57 202.75
 10 103.10 193.50
 11 101.78 198.33
 12 102.13 204.75
 13 #slifjsf ojfosij  oiuiso  joij
 14 104.56 208.34
 15 106.14 199.50
 16 105.98 200.00

这是我的代码:

 16     ifstream myfile;
 17     myfile.open (arguments[1]);
 18     string line;
 19     string sline;
 20     vector< vector<double> > values;
 21     double x;
 24 if (myfile.is_open())
 25     {
 26         getline(myfile, sline);
 27         cout << sline << endl;
 28         while (!myfile.eof())
 29         {
 30             if(line.at(0) != '#')
 31             {
 32                 myfile >> x;
 33                 values.push_back(vector<double>(x));
 34
 35                 for(int count = 0; count < values.size(); count++)
 36                 {
 37                     values.push_back( vector<double>(count) );
 38                     cout << values.at(0).at(0);
 39                 }
 40             }
 41         }
 42     }else cout << "The file doesn't exist" << endl;
 43 }

我得到的错误:

terminate called after throwing an instance of 'std::out_of_range'
  what():  basic_string::at
Aborted (core dumped)

有什么想法吗?

异常的原因可能是:

getline(myfile, sline);   // <== reading into "sline"
while (!myfile.eof())
{
    if(line.at(0) != '#') // <== checking "line"
    {

你正在读一个string,但查错了!

正确的检查是:

while (getline(myfile, sline)) {
    if (sline.at(0) != '#') {
        // note that before, for non-commented lines, you
        // just dropped sline completely, and went back to the
        // file for input. That is wrong, you need to 
        // parse the line you just got!
        std::vector<double> next_row;
        std::istringstream iss(sline);
        while (iss >> x) {
            next_row.push_back(x);
        }
        // etc.
    }
}

一旦修复,就不明显了,但这个循环:

for(int count = 0; count < values.size(); count++)
{
    values.push_back( vector<double>(count) );
    cout << values.at(0).at(0);
}

如果values不为空,则实际上是一个无限循环。这是因为在每次迭代中,我们都会在values中插入一个元素,这会增加它的大小。所以countvalues.size()每次迭代都会增加一个——你不断地移动目标。这是一个严重的逻辑错误。