【问题标题】:Align Integer using cout in C++在 C++ 中使用 cout 对齐整数
【发布时间】:2011-06-03 03:12:29
【问题描述】:

我需要 C++ 来使用 cout 来打印:

Header
     1
     2
     3
     4
     5
    10
    11
    12

而不是

Header
    1
    2
    3
    4
    5
    10
    11
    12

我应该如何使用 cout 格式化?

【问题讨论】:

    标签: c++ formatting cout


    【解决方案1】:

    使用 IO 操纵器setw

    #include <iostream>
    #include <iomanip>
    int main()
    {
        std::cout << "Header\n";
        for(int i=1; i<13; ++i)
            std::cout << std::setw(6) << i << '\n';
    }
    

    【讨论】:

    • @Mark:是的,你不仅可以控制宽度(用空格填充),还有setprecision(控制小数点后的数字)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    相关资源
    最近更新 更多