c++的输出:指定位数和对齐方式


  • setw(位数)
  • setfill(指定字符):是对全局有效的
  • 对齐方式:左对齐left,右对齐:right。默认是右对齐
  • 全局对齐:cout.setf(std::ios::left);
#include 
#include  
using namespace std;

int main()
{
    cout.setf(std::ios::left);  // 设置左对齐,全局有效

    for(int i = 0; i < 5; i++)
    {
        cout << setw(5) << i;
    }
    cout << endl;

    cout << right << setw(4) << setfill('*') << 2 << endl;
    cout << left << setw(3) << 2 << endl;

    return 0;
}