C++ formatted output to generate multiplication formula table
The main contents of C++ formatted output are: field width, character padding, and character alignment.
- Field width: realized by the setw function, which can be set before, during, and after the character.
- Character stuffing: a setfill implemented function, setfill function is followed setw behind populate the gap (space by default).
- Character alignment: specified by std::ios_base::left , std::ios_base::adjustfield , std::ios_base::right, etc.
The following three operations will generate a multiplication formula table:
#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;
}
The output is as follows: