#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    6
    Rep Power
    0

    C++:Load two demensional array from file?


    Hello there guys,I need to load a two dimensional array from file in my program.
    The matrix in the file is like:

    M N
    A11 A12 ....A1N
    .....................
    Am1 Am2 Amn

    Where M and N are the size of the matrix and they are expected to change when i want to show a smaller part of that matrix for example.
    Also another question:
    We have the same matrix and i want to cut it in two different matrixes - lets say its 10 rows and i want to cut in in the fifth row so the two new will show A - matrix from numbers above that row and B - matrix from numbers below that row.

    Any clues will be highly appreciated.
  2. #2
  3. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Oct 2012
    Posts
    6
    Rep Power
    0
    Any idea how to assign M and N to a "a" and "b" variables?
    How getline reads the lines in the text file?Are they readed as one line or every char is read separately?Can i start reading from the second row when i assign the two variables from the first to the array(just skip first row)?
    Please any guidance will be very much appreciated!
  4. #3
  5. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,387
    Rep Power
    1871
    An example.
    Code:
    $ cat bar.txt
    3 2
    1 2
    3 4
    5 6
    $ cat bar.cpp
    #include <iostream> 
    #include <fstream>
    #include <vector>
    using namespace std; 
    
    int main(void) 
    {
      vector<vector<int> > mat;
      ifstream fin("bar.txt");
      int rows, cols;
      if ( fin >> rows >> cols ) {
        for ( int r = 0 ; fin && r < rows ; r++ ) {
          vector<int> row;
          for ( int c = 0 ; fin && c < cols ; c++ ) {
            int temp;
            if ( fin >> temp ) {
              row.push_back(temp);
            }
          }
          mat.push_back(row);
        }
      }
      cout << "Number of Rows = " << mat.size() << endl;
      cout << "Number of Cols = " << mat[0].size() << endl;
      return 0;     
    }
    $ ./a.out 
    Number of Rows = 3
    Number of Cols = 2
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper

IMN logo majestic logo threadwatch logo seochat tools logo