Select 文本文件中的特定数据要导入到 C++ 中的二维数组中

Select specific data in text file to import in 2d array in c++

我是 C++ 编程的新手,我正在尝试打开一个文本文件,其中的大部分信息对我来说都没有用。该文件看起来像这样:

1

547

troncons

0 1 2 ...

2 2 3 4 5 7 ...

0 4 5 ...

...

如您所见,每一行的长度都不同。我首先要提取的是第二个元素 (547),它告诉我“troncons”之后的行数。之后,第一列中的数字告诉我信息在该行中的分布情况,如果它是 0,则表示第二个值是 x,第三个是 y,但如果第一个值不是 0,则第二个值是 x,第三个是 y 值的数量 n,下一个值是与 x 关联的 y。我只使用整数,我试图创建一个维度 (i,2) 的数组,其中每一行都是 (x,y) 对。每个末尾还有其他值,但我不需要它。

我知道我的代码应该如何工作,但我不知道如何用 C++ 编写它,因为我习惯了 Matlab

  1. get the number of line either by extracting the value in the second line or by getting the total number of line and subtracting 3.

  2. Iterate on each line and use a conditional statement to know if the first element is 0 or not.

  3. Then if it's 0, add the second and the third value to the array.

  4. If it is !=0, get the third value and iterate over that number to add in the array the x from the second value and the y from the 3+i value.

这就是我在 Matlab 中的做法,因为它们会自动将文本放入矩阵中,并且很容易通过索引访问它,但我觉得你不能用 C++ 做到这一点。

我看到了这两个链接: How do i read an entire .txt file of varying length into an array using c++?

Reading matrix from a text file to 2D integer array C++

但是第一个用的是vector或者一维数组,第二个直接把所有的信息都拿来用静态内存

这应该让你继续:

#include <fstream>
#include <vector>
#include <iostream>
#include <string>

struct XY {
   int x;
   int y;
};

using std::ifstream;
using std::vector;
using std::cerr;
using std::endl;
using std::string;

int main() {
   vector<XY> data;
   ifstream input("filename.txt");

   if (input.good()) {
      int skip;
      string troncons;
      int numLines;
      input >> skip;
      input >> numLines; // 547
      input >> tronscons;
      data.reserve(numLines); // optional, but good practice
      for (int i=0; i<numLines; ++i) {
         XY xy;
         int first;
         input >> first;
         if (first == 0) {
            input >> xy.x;
            input >> xy.y;
            data.push_back(xy);
         } else {               
            int n;
            input >> xy.x;
            input >> n;
            for (int j=0; j<n; ++j) {
               input >> xy.y;
               data.push_back(xy);
            }
         }
      }
   }

   return 0;
}