• Advertisement
Sign in to follow this  

Getting a map from a txt file

This topic is 4912 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey all, i have been having some trouble loading my map array from a txt file. Say that in my map file: //Map.txt 0,0,0,0,0 0,0,0,0,0 0,0,0,0,0 0,0,0,0,0 0,0,0,0,0 and in main i have: int Map[5][5]; How exactly do i put the numbers in the file into the array? I have done file reading before, but this is different, and i cant get it working right. Im using C++ and opengl Any Help would be appreciated

Share this post


Link to post
Share on other sites
Advertisement
first of all, thats a 5x5 grid so use:
int Map[5][5];
now, assuming that this is a static map size (ie always 5x5), you're in luck, if you change instead of , seperated valus, use " "

//Map.txt
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0

//now for code:
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FILE *fp; // file open handle
char filename[1024] = "Map.txt";
char buffer[1024];
int Map[5][5];

if((fp=fopen(filename, "r")) == NULL) {
printf("ERROR opening file %s\n\n", filename);
return false;
}

for(int i = 0; i < 5; i++) {
fgets(buffer, 1024, fp);
sscanf(buffer, "%d %d %d %d %d", &Map[0], &Map[1], &Map[2], &Map[3], &Map[4]);
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

I think thats right

Share this post


Link to post
Share on other sites
Well my map is a 13x10 Map ...
//Way it is in my prog, i want to put into txt file
int BackGroundLayer1[MAPHEIGHT][MAPWIDTH]={
{1,1,1,1,1,1,1,1,1,1,1,1,1},
{0,0,0,0,0,10,0,5,0,0,3,0,0},
{0,2,2,2,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,2,2,2,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,11,0,0,0,7,0,0,0,6,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0}
};
I tried out the last persons one, but it didnt work out to well,
I messed it up somehow :S, But i wasnt sure of what i was doing anyway, Never used fgets() or sscanf() before so it was kinda confusing because i didnt know what i was doing

Share this post


Link to post
Share on other sites
This has been asked already, look here

http://www.gamedev.net/community/forums/topic.asp?topic_id=269907

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement