c++ - 如何使用二维阵列打印电路板?

标签 c++

我想为游戏打印一个 5x5 的棋盘,目前我只能在填充数组时打印 5 行。我的董事会目前看起来像这样:

current image

从技术上讲,这是一个 2 行 5 列的板。

这是我期望的输出:

expected

问题是我需要同一 block 板的 5x5 版本,但它只打印 5 行(这是数组的大小)。

我已经多次尝试更改 for 循环,但到目前为止没有任何效果 这是我的代码:

    //
    // Created by renan on 31/08/2019.
    //

    #include <iomanip>
    #include <iostream>
    #include "Board.h"

    void Board::displayBoard() {
        for (int row = 0; row < ROWS; row++) {          //ROWS and COLS 
    are integers with value 5
                for (int col = 0; col < COLS; col++) {
                    board[row][col] = ' ';

                    if (row % 2 == 0) {
                        cout << " ---";
                    } else {
                        if (col == 0) {
                            cout << "|";
                        }
                        if(board[row][col] == ' '){
                            cout << setw(4) << "|";
                        } else {
                            cout << setw(1) << board[row][col] << " |";
                        }
                    }
                }
                cout << endl;


        }


    }

棋盘.h

    #include <iostream>
    using namespace std;

    class Board {
    private:
        static const int ROWS = 11;
        static const int COLS = 5;
        char board[ROWS][COLS];
    public:
        void displayBoard();


    };

最佳答案

我稍微更正并简化了您的代码。希望它能帮助您了解您的代码出了什么问题。

void drawHorizontalSeparater() {
    for (int i = 0; i < 5; i++) {
        cout << " ---";
    }
    cout << endl;
}

void drawSeparatedValues(int row) {
    cout << "|";

    for (int col = 0; col < 5; col++) {
        board[row][col] = ' ';

        cout << " " << board[row][col] << " |";
    }
    cout << endl;
}

void displayBoard() {
    drawHorizontalSeparater();
    for (int row = 0; row < 5; row++) {
        drawSeparatedValues(row);
        drawHorizontalSeparater();
    }
}

结果:

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

|   |   |   |   |   |

 --- --- --- --- ---

关于c++ - 如何使用二维阵列打印电路板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57764980/

相关文章:

c++ - 可移植比较和交换(原子操作)C/C++ 库?

c++ - 如何将组合标志结果反转为标志?

c++ - 等同于memcpy不同的结果?

c++ - 了解 C++ 模板方法定义语法

c++ - Protocol Buffer 错误版本

c++ - 如何在 C++ 中根据不同的值使用不同的命名空间?

c++ - 如何计算区间 [a,b]

c++ - 调整Canny边缘算法中的阈值

c++ - 工厂方法说明

c++ - 从标准 :string to add typedefs and enums 派生