C++ 2D dynamically allocated array printing weird numbers

  c++

I’m new to c++ and am currently trying to learn about dynamic memory allocation. I am using g++ complier on Linux and tried searching for a solution on new/delete instead of std::vector but to no avail.

I am trying to re-create this output but so when I tried to run my code, the output I gotten was this.

This is the file.

Here is my code so far.

    string gridx = "0-8";
    string gridy = "0-8";

    ifstream inputFile;
    inputFile.open(cityloc.c_str());

    // Using dynamic memory allocation
    int **grid = new int*[gridx[2]-'0'+ 2];
    for (int i = 0; i < (gridx[2]-'0'+ 2); i++)
    {
            grid[i] = new int[gridy[2]-'0'+ 2];
    }

    // Ensuring that the first digits in the array are set to 0
    for (int i = 0; i < sizeof(grid)/sizeof(grid[0]); i++)
    {
            for (int j = 0; j < sizeof(grid[0])/sizeof(grid[0][0]); j++)
            {
                    grid[i][j] = 0;
            }
    }

    // Reading the line and saving it to the array
    string line;
    if (inputFile.good())
    {
            while (getline(inputFile, line))
            {
                    // Getting the x, y and the City ID
                    grid[(line[1]-'0')][(line[4]-'0')] = (line[7]-'0');
            }
    }
    inputFile.close();

    // Printing first line of #     
    cout << "     ";
    for (int i = (gridx[2]-'0'+ 2); i >= 0; i--)
    {
            cout << "# ";
    }
    cout << endl;

    // Printing the range with the city id displayed
    for (int i = (gridy[2]-'0'); i >= 0; i--)
    {
            cout << "  " << i << "  #";
            for (int j = 0; j < 9; j++)
            {
                    cout << " ";
                    if (grid[j][i] == 0)
                    {
                            cout << " ";
                    }
                    else
                    {
                            cout << grid[j][i];
                    }
            }
            cout << " # " << endl;
    }

    // Printing last line of # with the range
    cout << "     ";
    for (int i = (gridx[2]-'0'+ 2); i >= 0; i--)
    {
            cout << "# ";
    }

    cout << endl << "       ";
    for (int i = 0; i < (gridx[2]-'0'+ 1); i++)
    {
            cout << i << " ";
    }
    cout << endl;

    // Deleting array to prevent memory leaks
    for (int i = 0; i < (gridx[2]-'0'+ 1); i++)
    {
            delete[] grid[i];
    }
    delete[] grid;

Thank you in advance for the help!

Source: Windows Questions C++

LEAVE A COMMENT