Cant Load array from File correctly??

Hi,

I have recently tried to make a simple game. I have based the level file like this:
1
2
3
4
NUMBER_OF_OBJECTS
X Y IMG
X Y IMG
X Y IMG

Example file:
1
2
3
4
5
4
700 500 2
32 32 2
64 64 2
128 128 2

So in this level there are 4 objects with those coordinates and img IDs.

I have wrote this simple C++ example that should fill the object array.
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
#define MAX_OBJ 100
#define MAX_PRO 3
#include <iostream>
#include <fstream>
using namespace std;
class c_Objekat
{
public:
	float x,y,img;

};
int brObj;
c_Objekat objekti[MAX_OBJ];

void Ucitaj()
{
	ifstream citac("nivo.txt",ios::in);
	citac >> brObj;
	for(int i = 1; i <= brObj; i++)
	{
		for(int j = 1; j <= MAX_PRO; j++)
		{
			citac >> objekti[i].x >> objekti[i].y >> objekti[i].img;
		}
	}
	citac.close();
}
void Listaj()
{
	for(int i = 1; i <= brObj; i++)
	{
		cout << "objekti[" << i << "]:  " << objekti[i].x << "  " << objekti[i].y << "  " << objekti[i].img << endl;
	}
}
int main()
{
	Ucitaj();
	Listaj();
	system("pause");
	return 0;
}


I have a class named c_Objekat that has three properties x, y coord and img ID.
So I've decalred an array of 100 objects that can be used in game for this.

My function Ucitaj() should read the file and fill the first 4 objects in array with their x,ya and img properties but that is not what happens.

When I call the Listaj() function I get this:
1
2
3
4
5
objekti[1]:  64  64  2
objekti[2]:  128  128  2
objekti[3]:  0  0  0
objekti[4]:  0  0  0
Press any key to continue . . .

My array is only filled with last 2 elements from file.

So what could be the problem?

Thanks in advance!
Last edited on
Solved!
Here's the correct code:
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
#define MAX_OBJ 100
#define MAX_PRO 3
#include <iostream>
#include <fstream>
using namespace std;
class c_Objekat
{
public:
	float x,y,img;

};
int brObj;
c_Objekat objekti[MAX_OBJ];

void Ucitaj()
{
	ifstream citac("nivo.txt",ios::in);
	citac >> brObj;
	for(int i = 1; i <= brObj; i++)
	{
			citac >> objekti[i].x >> objekti[i].y >> objekti[i].img;
	}
	citac.close();
}
void Listaj()
{
	for(int i = 1; i <= brObj; i++)
	{
		cout << "objekti[" << i << "]:  " << objekti[i].x << "  " << objekti[i].y << "  " << objekti[i].img << endl;
	}
}
int main()
{
	Ucitaj();
	Listaj();
	system("pause");
	return 0;
}
Topic archived. No new replies allowed.