Getting a map from a txt file

Started by
4 comments, last by jsloan 19 years, 7 months ago
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
Advertisement
You could look into using fscanf() to parse your file.

Incidentally, you do know that you've declared a 4x4 array but have 5x5 data, right?
lol yea i see that now, But its not like that in my prog :S
Its fixed now, and ill look into that link
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
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
This has been asked already, look here

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

This topic is closed to new replies.

Advertisement