1、字段宽度、填充和对齐
#include <iostream> #include <iomanip> int main() { using namespace std; cout << '|' << setfill('*') << setw(6) << 1234 << "|\n"; cout << '|' << left << setw(6) << 1234 << "|\n"; cout << '|' << setw(6) << -1234 << "|\n"; cout << '|' << right << setw(6) << -1234 << "|\n"; return 0; }
2、打印乘法表
#include <iostream> #include <iomanip> int main() { using namespace std; int const LOW = 1; int const HIGH = 10; int const COL_WIDTH = 4; // 所有数字必须右对齐 cout << right; // 首先打印表头 cout << setw(COL_WIDTH) << '*' << '|'; for (int i = LOW; i <= HIGH; i++) { cout << setw(COL_WIDTH) << i; } cout << '\n'; // 打印横线 cout << setfill('-') << setw(COL_WIDTH) << "" << '+' << setw((HIGH - LOW + 1) * COL_WIDTH) << "" << '\n'; // 重设填充字符 cout << setfill(' '); // 打印每一行 for (int row = LOW; row <= HIGH; row++) { cout << setw(COL_WIDTH) << row << '|'; // 打印列 for (int col = LOW; col <= HIGH; col++) { cout << setw(COL_WIDTH) << row * col; } cout << '\n'; } return 0; }