### How do you read from file to a 3D array?

closed account (yqD8vCM9)
1) There is a data file containing strings. You must read all the strings into a 3D array.

Is this the rright way?
So confused.
Last edited on
(deleted)
Last edited on
closed account (yqD8vCM9)
Something like this

Then what are x,y,z? Rows? Columns?
Last edited on
@defjamvan123

Your first version (with 2 loop) is correct if you want to store a 2D array of strings.

This

`char myArray[x][y][z];`

should be taken to be a 2D array (x by y) of char buffers (each z chars long)

If you need to store a 3D array of strings, then you'll need to either: (a) switch to using string rather than char, or (b) add another dimension.

Andy

PS Scaled down version:

 ``1234567891011121314151617181920212223242526272829303132`` ``````#include #include using namespace std; int main() { const int x = 4; const int y = 3; const int z = 32; char myArray[x][y][z]; ifstream fin("c:\\test\\arr_data.txt"); for ( int i = 0; i < x; i++ ) { for ( int j = 0; j < y; j++ ) { fin >> myArray[i][j]; } } for ( int i = 0; i < x; i++ ) { for ( int j = 0; j < y; j++ ) { cout << "myArray[" << i << "][" << j << "] = " << myArray[i][j] << endl; } } return 0; }``````

 ```one two three four five six seven eight nine ten eleven twelve```

It outputs:

 ``123456789101112`` ``````myArray[0][0] = one myArray[0][1] = two myArray[0][2] = three myArray[1][0] = four myArray[1][1] = five myArray[1][2] = six myArray[2][0] = seven myArray[2][1] = eight myArray[2][2] = nine myArray[3][0] = ten myArray[3][1] = eleven myArray[3][2] = twelve``````

Last edited on
closed account (yqD8vCM9)
@andywestken Thanks alot!
PS

 Then what are x,y,z? Rows? Columns?

For

`char myArray[x][y][z];`

it's an array, of x rows and y cols, of buffers of z chars

Andy

Topic archived. No new replies allowed.