选择文本文件中的特定数据导入到c++的2d数组中

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

本文关键字:c++ 数组 导入 2d 文本 文件 选择 数据      更新时间:2023-10-16

我是c++编程的新手,我正试图打开一个文本文件,其中大多数信息对我没有用处。文件看起来像这样:

1

547年

troncons

2 2 3 4 5 7…

你可以看到每一行都有不同的长度。我首先要提取的是第二个元素(547),它告诉我在"之后的行数。之后,第一列中的数字告诉我的信息是如何分布在直线如果是0,这意味着第二个值x和第三个是y,但如果第一个值不是0第二个值是x,第三是y值的数目n和n值x y相关。我只处理整数和我试图创建一个数组的维度(我,2)每一行是一个(x, y)夫妇。此外,在每个值的末尾还有其他值,但我不需要它。

我对我的代码应该如何工作有了一个想法,但我不知道如何用c++编写它,因为我习惯了Matlab

  1. 通过提取第二行的值或通过获得总行数并减去3来获得行数。

  2. 遍历每行,使用条件语句判断第一个元素是否为0。

  3. 如果为0,则将第二个和第三个值添加到数组中。

  4. 如果是!=0,获取第三个值并遍历该数字,在数组中添加第二个值中的x和3+i值中的y。

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

我看到了这两个链接:我如何读取整个。txt文件的不同长度到一个数组使用c++?

从文本文件读取矩阵到二维整数数组c++

但是第一个使用向量或一维数组,第二个直接获取所有信息并使用静态内存。

这应该会让你开始:

#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;
}