如何像这样格式化输出

How to format output like this

到目前为止我的代码是这样的:

void matrix::print(int colWidth) const
{
    cout << getRows() << " x " << getCols() << endl;
    cout << "-";
    for (unsigned int d = 0; d < getCols(); d++) {
        cout << "--------";
    }

    cout << endl;
    for (unsigned x = 0; x < getRows(); x++) {
        cout << "|";
        for (unsigned y = 0; y < getCols(); y++) {
            cout << setw(colWidth) << at(x, y) << " |";
        }
        cout << endl;
    }
    cout << "-";
    for (unsigned int d = 0; d < getCols(); d++) {
        cout << "--------";
    }

    cout << endl;
}

但输出取决于 colWidth,这将是每个打印数字之间的 space。那么,无论 colWidth 它应该对齐,我如何调整我的破折号以像下面这样打印。

一个输出应如下所示:

第二个输出是这样的:

如果列宽是一个参数,那么您的代码就差不多完成了。只需将 cout<<"--------" 变成:

std::cout << std::string(getCols()*(colWidth + 2) + 1, '-');

该代码打印一串破折号,其宽度为:矩阵列数乘以列宽加 2,再加 1:

  • 加 2,因为您要向每一列附加 " |"
  • 加 1,因为您要在每行的开头添加 '|'

您可能希望在 print 方法的开头检查空矩阵。

[Demo]

#include <initializer_list>
#include <iomanip>  // setw
#include <iostream>  // cout
#include <vector>

class matrix
{
public:
    matrix(std::initializer_list<std::vector<int>> l) : v{l} {}
    
    size_t getRows() const { return v.size(); }
    size_t getCols() const { if (v.size()) { return v[0].size(); } return 0; }
    int at(size_t x, size_t y) const { return v.at(x).at(y); }

    void print(int colWidth) const
    {
        std::cout << "Matrix: " << getRows() << " x " << getCols() << "\n";

        // +2 due to " |", +1 due to initial '|'
        std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
        
        for (unsigned x = 0; x < getRows(); x++) {
            std::cout << "|";
            for (unsigned y = 0; y < getCols(); y++) {
                std::cout << std::setw(colWidth) << at(x, y) << " |";
            }
            std::cout << "\n";
        }

        std::cout << std::string(getCols()*(colWidth + 2) + 1, '-') << "\n";
    }

private:
    std::vector<std::vector<int>> v{};
};

int main()
{
    matrix m{{1, 2}, {-8'000, 100'000}, {400, 500}};
    m.print(10);
}

// Outputs
//
//   Matrix: 3 x 2
//   -------------------------
//   |         1 |         2 |
//   |     -8000 |    100000 |
//   |       400 |       500 |
//   -------------------------