Hello, i would like to know whats wrong with the code i wrote about getting a map, for a pacman-like game i am trying to make using ncurses in which the map where the player can navigate is taken and shown on the screen from a .txt file.
The .txt file is map1.txt and heres the code:
the first one is the map that gets printed correctly and the second is the data that i have been trying to pass from the buffer to the map array, this i tried because i havent seen a way to pass data from a file to a two-dimensional arrays... Please, explain why is this happening and help with a better solution if you have one.
I tried using the operators >> but they stop and do not copy the whole line of stars("*") resulting into something like this:
*****************
*
**
*** ... and this goes on
while (!examplefile.eof()){
examplefile.getline(buffer,26);
cout << buffer << endl;
for(j=0;j<26;j++)
map[i][j]=buffer[j];
if(j==25) // This is not in the for loop above. j==26 every time here.
i++; //i++ never happens. map[i][j] is 95% uninitialized!
}
#include <fstream>
#include <iostream>
#include <string>
usingnamespace std;
int main () {
char buffer[26];
char map[20][26];
int i, j
ifstream examplefile ("map1.txt", ios::binary);
for(i=0;!examplefile.eof();i++){ //i++ moved here, it's a for loop now!
examplefile.getline(buffer,26);
cout << buffer << endl;
for(j=0;j<26;j++)
map[i][j]=buffer[j];
}
for(i=0;i<20;i++)
{ // added bracket here
for(j=0;j<26;j++) // removed bracket here
cout << map[i][j];
cout << endl; //j==25 would work, but why not just take it out of that for loop and drop the if?
}
return 0;
}
1) you're using a "while not eof" loop, which means you're reading past the end of file, and if your file has 20 lines or more, you're writing past the end of the array map
replace
1 2 3
while (!examplefile.eof()){
examplefile.getline(buffer,26);
with while (examplefile.getline(buffer,26) && i<20){
2) you're not incrementing i, ever.
replace
1 2
if(j==25)
i++;
with just i++;
or tuck it inside the loop as you do in the output
3) you're printing map[i][26], which is a null character. Either loop until j<25 in output, or just replace
@Stewbond i used the For loop and it turned out to be a wrong choice because i had a "segmentation fault" error which i believe is because of the condition(!file.eof()), although using the condition Cubbi suggested will work. Anyway thanks for sorting out the brackets and pointing out the increment error!
@Cubbi i did what you suggested, changed the condition and it worked, never thought of that solution thank you too!
Well, i will post the correct code below for anyone having the same problem, and i might later on, after the completition of the project, post a solution using dynamic memory allocation, in order to widen the borders of the game and so on... So the correct code :