将文件的列读入数组

Reading file's columns into array

本文关键字:数组 文件      更新时间:2023-10-16

我正在读取具有一定列数的文件,每行都有不同数量的列,它们是不同长度的数值,并且我有固定的行数(20)如何将每一列放入数组中?

假设我有如下数据文件(每列之间有选项卡)

20   30      10
22   10       9       3     40 
60    4
30    200   90
33    320    1        22    4

如何将这些列放入不同的数组中,该列 1 转到一个 arrary,第 2 列转到另一个 arrary。只有第 2 列的值超过 2 位,其余列的值超过 1 位或两位,并且某些列也为 null,但 1、2 和 3 除外

int main()
{     
    ifstream infile;
    infile.open("Ewa.dat");
    int c1[20], c2[20], ... c6[20];
    while(!infile.eof()) { 
        //what will be the code here?
        infile >>lines;
        for(int i = 1; i<=lines; i++) {
            infile >> c1[i];     
            infile >> c2[i];
             .
             .
            infile >> c6 [20]; 
        }
    }
}

这是主要思想:

使用 2D 数组而不是许多 1D 数组。
使用 std::string 读取每一行。
然后使用: istringstream is(str);这将有助于解析字符串并放入数组中,如下所示:

while(...) {
    ....
    getline(infile, str);
    istringstream is(str);
    j=0;
    while(is)
        {
            is >> c[i][j];
        }
    i++;
    ....
    }

剩下的就交给你了。

利用

一些C++库类可能更容易,如std::vectorstd::istringstreamstd::string

#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
int main() {
  std::vector<std::vector<int> > allData;
  std::ifstream fin("data.dat");
  std::string line;
  while (std::getline(fin, line)) {      // for each line
    std::vector<int> lineData;           // create a new row
    int val;
    std::istringstream lineStream(line); 
    while (lineStream >> val) {          // for each value in line
      lineData.push_back(val);           // add to the current row
    }
    allData.push_back(lineData);         // add row to allData
  }
  std::cout << "row 0 contains " << allData[0].size() << " columnsn";
  std::cout << "row 0, column 1 is " << allData[0][1] << 'n';
}