me_newbie
me_newbie

Reputation: 25

Reading file's columns into array

i'm reading file which has some number of columns each line has different number of columns and they are numerical values of different length, and i have fix number of rows (20) how to put each column in to array?

suppose i have data file like following (there is tab between each column)

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

how to put these columns into different array,, that column 1 goes to one arrary and column 2 goes to another. Only column 2 has more than 2 digit values and the rest of columns has 1 or two digit values, and some columns are null too except 1, 2, and 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]; 
        }
    }
}

Upvotes: 2

Views: 5596

Answers (2)

Nate Kohl
Nate Kohl

Reputation: 35914

It might be easier to take advantage of some of some C++ library classes, like std::vector, std::istringstream, and std::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() << " columns\n";
  std::cout << "row 0, column 1 is " << allData[0][1] << '\n';
}

Upvotes: 1

P.P
P.P

Reputation: 121397

Here's the main idea:

Use a 2D array instead of many 1D arrays.
Read each line using std::string.
Then use: istringstream is(str); which will help parse the string and put into the arrays like this:

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

I'll leave the rest to you.

Upvotes: 1

Related Questions