【问题标题】:How to format right and left justification on the same line?如何在同一行格式化左右对齐?
【发布时间】:2019-12-18 05:02:42
【问题描述】:

如果我正在制作一个数据表来显示几个函数的结果,我如何使用 setw()、left 和 right 关键字来创建一个格式如下的表:

Height                       8
Width                        2
Total Area                  16
Total Perimeter             20

注意表格的整体“宽度”是恒定的(大约 20 个空格)。但是左边的元素是左对齐的,右边的值是右对齐的。

【问题讨论】:

标签: c++ setw


【解决方案1】:
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>

struct Result
{
    std::string Name;
    int Value;
};

int main()
{    
    std::vector<Result> results = { {"Height", 8}, {"Width", 2}, {"Total Area", 16}, {"Total Perimeter", 20} };

    for (auto result : results)
    {
        std::cout << std::setw(16) << std::left << result.Name;
        std::cout << std::setw(4) << std::right << result.Value << std::endl;
    }

    return 0;
}

【讨论】:

    【解决方案2】:

    你可以这样做:

    // "Total Perimiter" is the longest string
    // and has length 15, we use that with setw
    cout << setw(15) << left << "Height"          << setw(20) << right << "8"  << '\n';
    cout << setw(15) << left << "Width"           << setw(20) << right << "2"  << '\n';
    cout << setw(15) << left << "Total Area"      << setw(20) << right << "16" << '\n';
    cout << setw(15) << left << "Total Perimeter" << setw(20) << right << "20" << '\n';
    

    【讨论】:

    • 有没有办法让每一行都在同一个 setw() 上?换句话说,我不能只定义 1 个 setw() 并让表格的元素在其中左右对齐吗?
    猜你喜欢
    • 2015-08-13
    • 2013-05-22
    • 2015-05-07
    • 2023-03-31
    • 2014-05-02
    • 1970-01-01
    • 2015-01-09
    • 1970-01-01
    • 2019-01-21
    相关资源
    最近更新 更多