C++11格式化输出生成乘法口诀表

C++格式化输出生成乘法口诀表

C++格式化输出的主要内容有:字段宽度、字符填充、字符对齐。

  • 字段宽度:由setw函数实现,可以在字符前、中、后设置。
  • 字符填充:由setfill函数实现,setfill函数是跟在setw后面填充相应的空位(默认是空格)。
  • 字符对齐:由std::ios_base::left, std::ios_base::adjustfield,std::ios_base::right等指定。
    下面将通过以上三种操作生成一个乘法口诀表:
#include <iostream>
#include <iomanip>

using namespace std;

int main(int argc, char** argv)
{
    int const low{1};
    int const high{9};
    int const colWidth{4};

    // 所有数据右对齐
    cout << right;
    // 绘制表头
    cout << setw(colWidth) << "*" << "|";
    for(int i{low};i <= high;i = i + 1){
        cout << setw(colWidth) << i;
    }
    cout << endl;
    cout << setfill('-') << setw(colWidth) << "" <<'+' 
        << setw((high-low+1) * colWidth) << "" << endl;

    // 重置cout
    cout << setfill(' ');

    // 绘制表格数据
    for(int row{low};row <= high;row = row + 1){
        cout << setw(colWidth) << row << "|";
        for(int col{low};col <= high;col = col + 1){
            cout << setw(colWidth) << row * col;
        }
        cout << endl;
    }

    return 0;
}

输出结果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wujuxKkoolerter/article/details/114093016