0

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.

2
  • 3
    input.get() will read newline characters. If your rows appear on each line, then either use the formatted input for char (i.e. char ch; input >> ch;) which will skip whitespace, or read the entire line as a string and copy the data out. Commented Apr 3, 2024 at 23:38
  • The code in the OP leaks memory when operator new throws a std::bad_alloc. Consider switching to std::vector<std::vector<Cell>> (or just std::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. Commented Apr 4, 2024 at 1:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.