2016年05月17日(火) [長年日記]
■ [c++] C++のストリームに最小フィールド幅を指定する
ストリーム出力時に最小フィールド幅を設定するにはstd::setw()を使う。
以前にメモした精度指定、桁数指定と組み合わせた例をメモ。std::setw()の効果は直後の値にしか効かないようなので注意が必要。
#include <iomanip>
#include <iostream>
int main()
{
const auto v0 = 2.0 / 3.0;
const auto v1 = 2.0 / 3.0 * 1000;
const auto v2 = 2.0 / 3.0 * 1000 * 1000;
std::cout << std::fixed << std::setprecision(3);
std::cout << std::setw(8) << v0 << ", " << v0 << std::endl;
std::cout << std::setw(8) << v1 << ", " << v1 << std::endl;
std::cout << std::setw(8) << v2 << ", " << v2 << std::endl;
}
0.667, 0.667 666.667, 666.667 666666.667, 666666.667
[ツッコミを入れる]