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 @   荒年、  阅读(1331)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示