std::ios_base:: width
From cppreference.net
|
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 = { "言語"sv, "作者"sv, "生年月日"sv, "没年月日"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); }
出力:
+------------+-------------------+------------+------------+ | 言語 | 作者 | 生年月日 | 没年月日 | +------------+-------------------+------------+------------+ | 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 | | +------------+-------------------+------------+------------+
関連項目
|
浮動小数点演算の10進精度を管理する
(public member function) |
|
|
次の入出力フィールドの幅を変更する
(function) |