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

  • 头文件<iomanip>
  • setw(位数)
  • setfill(指定字符):是对全局有效的
  • 对齐方式:左对齐left,右对齐:right。默认是右对齐 直接写left,right或者写setiosflags(ios::left),setiosflags(ios::right)
  • 全局对齐:cout.setf(std::ios::left);
#include <iostream>
#include <iomanip> 
using namespace std;

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

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

    //cout << setiosflags(ios::right) << setw(4) << setfill('*') << 2 << endl;  // 设置对齐方式也可以setiosflags
    cout << right << setw(4) << setfill('*') << 2 << endl;
    cout << left << setw(3) << 2 << endl;

    return 0;
}

image

posted @ 2022-04-09 08:48  荒年、  阅读(1168)  评论(0编辑  收藏  举报