Reading file's columns into array

Hi Guys!

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)

1
2
3
4
5
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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]; 
           }
    }
}


Thanks in advance

Regards,

Ewa

Last edited on
Hi !

i almost solved the problem, but after solving i noticed there is something wrong

let see my code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#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';
}


now the problem is that my array is filled with garbage values, where i don't have a value in file?

how to solve this?

Thanks in Advance

Ewa
Hi... here is the solution if anyone else need it

1
2
3
4
5
6
7
8
 for (int i=0; i<allData.size(); ++i)
    {
        for (int j=0; j<allData[i].size(); ++j)
        {
            cout << allData[i][j] << " ";
        }
        cout << "\n";
    }


Regards
Topic archived. No new replies allowed.