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

Sep 1, 2013 at 9:23pm
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.
Thank You in advance.
Last edited on Sep 3, 2013 at 10:42pm
Sep 1, 2013 at 9:27pm
(deleted)
Last edited on Sep 1, 2013 at 11:21pm
Sep 1, 2013 at 9:49pm
closed account (yqD8vCM9)
Something like this

Then what are x,y,z? Rows? Columns?
Last edited on Sep 3, 2013 at 10:42pm
Sep 1, 2013 at 10:13pm
@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:

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
27
28
29
30
31
32
#include <iostream>
#include <fstream>
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;
}


Reading this file in (arr_data.txt)

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


It outputs:

1
2
3
4
5
6
7
8
9
10
11
12
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 Sep 1, 2013 at 10:26pm
Sep 1, 2013 at 11:03pm
closed account (yqD8vCM9)
@andywestken Thanks alot!
Sep 1, 2013 at 11:47pm
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.