Arrays and Multidimentional Arrays

I want to expand my comfort zone and start "reading from files more". In school, we are at multi-dimensional arrays. For this one program we have this week, its a 4D array and we need to print out the values at specific places (ie. x[1][2][3][4].

My question is: Why am I not able to put all 120 data members in a file then read that as a 4D array? I read that this process only works with 1D and 2D arrays. That my best solution would be to read as a 1D array and then reshape the data to a 4D ray, given I know the dimensions.

What is the benefit of doing it this way? It seems to me that the best course of action would be to initialize the array in int main(). (we have 2 programs like this example this week and that's how I did it for the first one, and seems like how I'll do it for this one as well).

This is more of a why is this so rather then a, please help me, type of question.

Thanks in advance.

David
> That my best solution would be to read as a 1D array and then
> reshape the data to a 4D ray, given I know the dimensions.

No, you can read either all of it or parts of it from an input stream as a 4D array. For example:

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
#include <iostream>

enum { IMAX = 5, JMAX = 4, KMAX = 6, LMAX = 3 };

void read_sparse_array_from_stream( int (&a) [IMAX][JMAX][KMAX][LMAX], std::istream& stm )
{
    std::size_t i, j, k, l ;
    int value ;
    while( stm >> i >> j >> k >> l >> value &&
           i<IMAX && j<JMAX && k<KMAX && l<LMAX ) a[i][j][k][l] = value ;
}

#include <sstream>

int main()
{
    int a[IMAX][JMAX][KMAX][LMAX] = {0} ;

    std::istringstream stm( "4 0 4 0 567\n"
                            "3 1 2 1 120\n"
                            "2 2 3 1 800\n"
                            "1 3 5 2 345\n" ) ;
    read_sparse_array_from_stream( a, stm ) ;

    std::cout << a[1][1][1][1] << ' ' << a[3][1][2][1] << ' ' << a[2][2][3][1] << '\n' ;
}

Topic archived. No new replies allowed.