I am working on a maze solving algorithm. I input a text file formatted with 2 numbers at the top defining the width and height. Then a G for goal, S for start, # are walls, . are open spaces.
Example input:
3 3
..G
S##
#..
I have defined this function to make a data struture representation of the maze.
Cell** readFile(string filename, int& row, int& col) {
fstream input;
input.open(filename);
string c;
int x,y;
getline(input, c, ' ');
x = stoi(c);
getline(input, c, '\n');
y = stoi(c);
Cell** maze = new Cell*[x];
for (int i = 0; i < x; i++) {
maze[i] = new Cell[y];
}
for(int i = 0; i < x; i++) {
for(int j = 0; j < y; j++) {
maze[i][j].x = i;
maze[i][j].y = j;
char ch = input.get();
cout << ch << endl; //Important Line
maze[i][j].symbol = ch;
}
}
row = x;
col = y;
return maze;
}
This compiles but when I execute it I get the following output:
..G S## #
As you can see this has some spaces that shouldn't be there. As well as not including all of the symbols. Can someone explain this?
I've tried reviewing the fstream::get() documentation and looked at other similar problems. Ive tried using the eof() as well but that had no impact. I tried checking to see if input.get() fails as well but that returned the same output.
input.get()will read newline characters. If your rows appear on each line, then either use the formatted input forchar(i.e.char ch; input >> ch;) which will skip whitespace, or read the entire line as a string and copy the data out.newthrows astd::bad_alloc. Consider switching tostd::vector<std::vector<Cell>>(or juststd::vector<Cell>, if you don't mind mapping it onto a 2D array). Otherwise, write a proper RAII class to hold a Maze, one that follows the Rule of Three.