Hi im writing tile-based game and i have problem with loading tile ID from file. Here`s the code.
const int MAP_X=10, MAP_Y=10;
main()
{
CTile map[MAP_X][MAP_Y]; // CTile is a class that contain all info about tile
std::ifstream file("map.txt");
if (file.is_open())
{
while (file.good())
{
int i,t;
for (i=0; i<MAP_Y; i++)
for (t=0; t<MAP_X; t++)
{
std::string line;
std::getline(file,line,' ');//should stop getting data when there is a space " " in file
map[t].type=atoi(line.c_str()); // convert string and assign to array
}
}
file.close();
for (i=0; i<MAP_Y; i++)
for (t=0; t<MAP_X; t++)
{
blit(tile,buffer,map[t].type*50,0,t*50,i*50+15,50,50);
}
}
Yes, because .type is connected with my bmp file that contains all the tiles and the tile size is 50. So each value reffers to different place in bmp file.
blit() function is taken from allegro.
Try adding some basic error checks:[/quote]
I added allegro_message("error loading file"); as You suggested but it turns out the file is opened correctly and if i try to debug my program screen freezes and i have to ctrl+alt+del him :/
(There are obviously alot of code missing from what you've posted)[/quote]
Not too much and there is no chance that map[x][y].type changes because of other functions. It is used only in loading from file and showing it on screen.
atoi() returns "0" when it cannot convert the string to an integer. You may notice that it is hard to tell this error code from the domain of valid integers!
One alternative is to use the stream extraction operators, like so:
const int MAP_X=10, MAP_Y=10;
int main()
{
CTile map[MAP_X][MAP_Y];
std::ifstream file("map.txt");
for(int x = 0 ; x < MAP_X ; ++x)
{
for(int y = 0 ; y < MAP_Y ; ++y)
{
if(!(file >> map[x][y]))
{
// Error handling
}
}
}
render(map);
}
This doesn't try very hard to match the structure of the file (it would be perfectly happy if you put all the numbers on a single line). It is a start.