how to read array from a file

If I have an array for example A[2][4][5] and i need to read n values from a file like if n=11:
File input to be like:
11
1 2 3 4 5 6 7 8 9 10 11.
how do you do it?
I tried this, but it doesn't seem to be working properly

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
  #include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ifstream IN("input");
	ofstream OUT("output");
	if ( IN && OUT)
	{
	int A[2][4][5];
		int n,i=0, j=0, z=0, x, y;
		IN>> n;
		cout<<n<<endl;
		for(int val=0;val<n;val++)
			{
            	IN>>A[i][j][z];
				z++;
				if(z==5)
				{
					z=0;
					j++;
				}
				if(j==4)
				{
					j=0;
					i++;

				}
				i++; 
			}
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()
{
	ifstream IN("input.txt");

	int k;
	IN >> k;
	int X[2][4][5];
	
	for(auto &a:X)
		for(auto &b:a)
			for(auto &c:b)
				c=0; // initialize all vavlues to 0	
	
	for(auto &a:X)
		for(auto &b:a)
			for(auto &c:b){
				if(k==0) break;
				IN >> c;
				k--; 
			}
			
	for(auto &a:X)
		for(auto &b:a)
			for(auto &c:b)
				cout << c << " ";		


return 0;
}
and what if i don't want to use auto & ect because I haven't learnt it yet?
how should I write it instead?
Thanks for replying =)
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
	ifstream IN("input.txt");

	int input;
	IN >> input;

	int X[2][4][5];

	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			for (int k = 0; k < 5; k++)
			{
				X[i][j][k] = 0; // initialize all vavlues to 0	
			}
		}
	}

// read input
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			for (int k = 0; k < 5; k++)
			{
				IN >> input;
				X[i][j][k] = input; 
			}
		}
	}

// display input
	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			for (int k = 0; k < 5; k++)
			{
				std::cout << X[i][j][k] << " ";
			}	

			std::cout << std::endl;
		}

		std::cout << std::endl;
	}

	system("pause");
	return 0;
}
Last edited on
that's really what I needed!
Thanks a lot to everyone! =D
@rafae11,
X[1][3][4] = ?
Topic archived. No new replies allowed.