Reputation: 45
I have a file called map.txt
, that looks like :
xxxxxxxxxxxxxxxxxx x Ox xx x x xx xx xxxxxx x xx x x x xxxx x x x x x x x x x x x x x x x x x x x x x x x x x xxxxxxxxxxxxxxxxxx
It represents a maze. I have to read this file char by char and store it in a bidimensional array char data [][]
but i'm having problems to use fgetc
. here is my code:
int readMapFromFile(char *filename) {
FILE *file = fopen(filename, "r");
char element;
printf("reading map from file %s...\n", filename);
int c;
if(file == NULL)
return 1;
int j =0;
int i =0;
while((c = fgetc(file))!= EOF) {
element = (char) c;
if(element == '\n') {
j = 0;
i++;
continue;
} else if(element == 'O') {
player.exitX = j;
player.exitZ = i;
}
data[i][j] = element;
j++;
}
fclose(file);
return 0;
}
It seems to skip the whitespaces and i have no idea how to make it work. As request i added how i display the data's content:
int i;
int j;
for (i =0 ; i < map.x ; ++i);
{
for(j = 0 ; j < map.z ; ++j) {
printf("%s \n", &data[i][j]);
}
}
Expected output :
xxxxxxxxxxxxxxxxxx x Ox xx x x xx xx xxxxxx x xx x x x xxxx x x x x x x x x x x x x x x x x x x x x x x x x x xxxxxxxxxxxxxxxxxx
My output :
xxxxxxxxxxxxxxxxxxxOxxxxxxxxxxxxxxxxxxxxxxx
As you can see not the entire maze is saved.
Upvotes: 1
Views: 101
Reputation: 50775
It's not about skipping whitespace. You just never increment j
.
The code in the if(element == '\n')
statement should be like this:
if(element == '\n'){
j++;
i = 0;
continue;
}
If you had named your variables x
and y
instead of i
and j
, you probably would have found out by yourself.
And your map display function is totally wrong, it should be:
int i;
int j;
for (i = 0 ; i < map.x ; ++i) {
for(j = 0 ; j < map.y ; ++j) {
printf("%c", data[i][j]);
}
printf ("\n");
}
Upvotes: 1