CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Threaded View

  1. #1
    Join Date
    May 2012
    Posts
    19

    Post Reading file into array

    Hi Guys!

    i'm reading a file which has 20 rows and random number of columns, i want to put them in array/vector which i did but the problem is that array is filling a cell with a garbage value at location where i don't have a value in the data file.

    suppose i have data file like following (there is tab between each column and each row has different number of columns)

    Code:
    20   30      10
    22   10      9       3      40 
    60    4
    30   200     90
    33   320             22
    here is my code

    Code:
    #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';
    }
    your help will be appreciated

    Regards,
    Ewa
    Last edited by me_newbie; May 10th, 2012 at 07:20 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured