Проблема с печатью динамического 2d массива (проблема выполнения)

#c #arrays #multidimensional-array #printing #dynamic-memory-allocation

Вопрос:

Я написал этот код здесь, но моя проблема в том, что всякий раз, когда я нажимаю кнопку «Выполнить» и выполняю свою программу, значения в порядке, но каждый элемент 2D-массива распечатывается в отдельной строке, это не печать квадрата с его размерами (размер n x n), как я хотел, как я могу это исправить?

мой код

это должно быть так, как я хочу, чтобы это выглядело

 #include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int countingNumOfMs(char** surface, int rows, int cols, int dimensions)
{
    int counter = 0;
    int i, j = 0;
    for (i = (rows - 1); i <= (rows   1); i  ) {
        for (j = (cols - 1); j <= (cols   1); j  ) {
            if (i < 0 || i >= dimensions || j < 0 || j >= dimensions)
                continue;

            else if (i == rows amp;amp; j == cols)
                continue;
            else if (surface[i][j] == 'M')
                counter  ;
        }
    }
    return counter;
}

bool turnIntoM(char** surface, int rows, int cols, int dimensions)
{
    int microOrganismCount = countingNumOfMs(surface, rows, cols, dimensions);
    if (surface[rows][cols] == 'M') {
        if (microOrganismCount != 2 amp;amp; microOrganismCount != 3)
            return false;
    }
    else {
        if (microOrganismCount == 3)
            return true;
    }
}

void nextSurface(char** surface, int dimensions)
{
    int rows, cols;
    char temp[dimensions][dimensions];

    for (rows = 0; rows < dimensions; rows  ) {
        for (cols = 0; cols < dimensions; cols  ) {
            if (turnIntoM(surface, rows, cols, dimensions)) {
                temp[rows][cols] = 'M';
            }
            else {
                temp[rows][cols] = '-';
            }
        }
    }

    for (rows = 0; rows < dimensions; rows  ) {
        for (cols = 0; cols < dimensions; cols  ) {
            surface[rows][cols] = temp[rows][cols];
        }
    }
}

void showCurrentIteration(char** surface, int dimensions)
{
    int rows, cols;
    for (rows = 0; rows < dimensions; rows  ) {
        cout << "[";
        for (cols = 0; cols < dimensions; cols  ) {
            cout << surface[rows][cols];
            cout << "]" << endl;
        }
    }
    cout << endl;
}

char** makeAnIteration(int dimensions)
{
    srand(time(0));

    char** surface = new char*[dimensions];

    int rows, cols;
    for (rows = 0; rows < dimensions; rows  )

        surface[rows] = new char[dimensions];

    int counter = 0;

    for (rows = 0; rows < dimensions; rows  ) {
        for (cols = 0; cols < dimensions; cols  )

            surface[rows][cols] = '-';
    }

    while (counter < (2 * dimensions)) {
        rows = rand() % dimensions;
        cols = rand() % dimensions;
        if (surface[rows][cols] == 'M')
            continue;

        surface[rows][cols] = 'M';
        counter  ;
    }

    return surface;
}

int main()
{
    int dimensions;
    cout << "Enter dimensions of the surface in size of (n x n) nEnter the value of n: " << endl;
    cin >> dimensions;
    char** surface = makeAnIteration(dimensions);

    cout << "Enter the number of iterations: " << endl;
    int iterations;
    cin >> iterations;

    for (int i = 0; i < iterations; i  ) {
        showCurrentIteration(surface, dimensions);
        nextSurface(surface, dimensions);
    }

    return 0;
}
 

Комментарии:

1. Вы знаете, что такое отладчик?

2. @RoQuOTriX да, я знаю, что такое отладчик, проблема в форме напечатанного 2d-массива, кроме этого, нет ничего плохого, он печатает каждый элемент в отдельной строке

3. @alienhana-Вот почему я ненавижу стиль форматирования «скобка в первой строке». Если вы посмотрите на данный ответ, вы ясно увидите, что cout он находится на неправильной линии.

Ответ №1:

Вы разместили линию

 cout << "]" << endl;
 

в неправильном месте. Это должно быть после внутреннего цикла, а не внутри него.

 void showCurrentIteration(char **surface, int dimensions)
{
    int rows, cols;
    for (rows = 0; rows < dimensions; rows  )
    {
        cout << "[";
        for (cols = 0; cols < dimensions; cols  )
        {
            cout << surface[rows][cols];
            // wrong place
            // cout << "]" << endl;
        }
        // it should be here
        cout << "]" << endl;
    }
    cout << endl;
}