std::ios_base::width

来自cppreference.com
< cpp‎ | io‎ | ios base
 
 
 
 
streamsize width() const;
(1)
streamsize width( streamsize new_width );
(2)

管理某些输出操作时生成的最小字符数,和某些输出操作时生成的最大字符数。

1) 返回当前字段宽度。
2) 设置字段宽度为给定值。返回先前的字段宽度。

参数

new_width - 设置的新字段宽度

返回值

调用函数前的字段宽度。

注解

一些 I/O 函数在返回前调用 width(0),见 std::setw(这导致此域仅在下次 I/O 函数,而不再任何后继 I/O 时有效)。

此修改器在输入和输出上拥有的确切效果,在各个不同的 I/O 函数之间有别,效果单独描述于每个 operator<<operator>> 重载的页面。

示例

#include <algorithm>
#include <array>
#include <iomanip>
#include <iostream>
#include <span>
#include <string_view>
using namespace std::string_view_literals;
 
constexpr std::array table_header =
{
    "Language"sv, "Author"sv, "Birthdate"sv, "RIP date"sv
};
 
using row_t = std::array<std::string_view, table_header.size()>;
using widths_t = std::array<std::size_t, table_header.size()>;
 
constexpr std::array table_body = std::to_array<row_t>
({
    {"C", "Dennis Ritchie", "1941-09-09", "2011-10-12"},
    {"C++", "Bjarne Stroustrup", "1950-12-30"},
    {"C#", "Anders Hejlsberg", "1960-12-02"},
    {"Python", "Guido van Rossum", "1956-01-31"},
    {"Javascript", "Brendan Eich", "1961-07-04"}
});
 
constexpr widths_t calculate_column_widths(std::span<const row_t> table)
{
    widths_t widths{};
    for (const row_t& row : table)
        for (size_t i = 0; i != row.size(); ++i)
            widths[i] = std::max(widths[i], row[i].size());
    return widths;
}
 
void print_row(const row_t& row, const widths_t& widths)
{
    std::cout << '|';
    for (size_t i = 0; i != row.size(); ++i)
    {
        std::cout << ' ';
        std::cout.width(widths[i]);
        std::cout << row[i] << " |";
    }
    std::cout << '\n';
};
 
void print_break(const widths_t& widths)
{
    const std::size_t margin = 1;
    std::cout.put('+').fill('-');
    for (std::size_t w : widths)
    {
        std::cout.width(w + margin * 2);
        std::cout << '-' << '+';
    }
    std::cout.put('\n').fill(' ');
};
 
int main()
{
    constexpr widths_t widths = calculate_column_widths(table_body);
 
    std::cout.setf(std::ios::left, std::ios::adjustfield);
    print_break(widths);
    print_row(table_header, widths);
    print_break(widths);
    for (const row_t& row : table_body)
        print_row(row, widths);
    print_break(widths);
}

输出:

+------------+-------------------+------------+------------+
| Language   | Author            | Birthdate  | RIP date   |
+------------+-------------------+------------+------------+
| C          | Dennis Ritchie    | 1941-09-09 | 2011-10-12 |
| C++        | Bjarne Stroustrup | 1950-12-30 |            |
| C#         | Anders Hejlsberg  | 1960-12-02 |            |
| Python     | Guido van Rossum  | 1956-01-31 |            |
| Javascript | Brendan Eich      | 1961-07-04 |            |
+------------+-------------------+------------+------------+

参阅

管理浮点操作的精度
(公开成员函数)
更改下个输入/输出字段的宽度
(函数)