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

    Join Date
    Jul 2002
    Location
    Tallahassee
    Posts
    55
    Rep Power
    14

    Question Reading file inputs and placing values into 2D array


    Hey all,
    I need to read an input file(any arbitrary file) that has matrix elements in it.

    Code:
    Ex:
    2 3
    9 7 5
    8 4 10
    1 6
    
    2 - int numrows;
    3 - int numcols;
    {(9,7,5),(8,4,10)} - matrix elements
    1 - int start;
    6 - int goal;
    I need to read the matrix elements and place them in a 2-D array.

    Code:
    |9 7 5|
    |8 4 10|
    I am guessing we need to use the numrows and numcols but we can ignore the start and goal variables for now. Would someone please help me along with this? Any feedback is appreciated as always. Thank you.
  2. #2
  3. No Profile Picture
    Junior Member
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2002
    Posts
    10
    Rep Power
    0

    RE


    after fopening the file and associating it with a handle

    Code:
    int num_col, num_row;
    int start, goal;
    int **arr; 
    fscanf(handle, "%d %d \n", num_col, num_row);
    arr = new int*[num_row];
    for (int i = 0; i < num_row; i++)
    { 
      arr[i] = new int[num_col];
      for (int j = 0; j < num_col; j++)
      {
        fscanf(handle, "%d \n", arr[i][j]);
      }
    }
    fscanf(handle, "%d %d \n", start, goal);
    this should read the needed data in the dinamic array (int **arr)
    you will have to delete the array after using it
    if you are writing the code in the C, not C++, use

    Code:
    arr = (int **)malloc(num_row*sizeof(int*));
    and
    arr = (int*)malloc(num_col*sizeof(int));
    instead of new
    Hope it'll help

IMN logo majestic logo threadwatch logo seochat tools logo