整数と浮動小数点数を書式化して表示

明解C言語 入門編 > 2. 演算と型 >

整数と浮動小数点数を書式化して表示

C++


#include <iostream.h>
#include <iomanip.h>

int main(int argc, char* argv[])
{

cout << "[" << 123 << "]" <<endl;
cout << "[" << setfill('0') << setw(4) << 123 << "]" <<endl;
cout << "[" << setfill(' ') << setw(4) << 123 << "]" <<endl;
cout << "[" << setfill(' ') << setw(4) << left << 123 << "]" <<endl;

cout << "[" << 12345 << "]" <<endl;
cout << "[" << setfill('0') << setw(3) << 12345 << "]" <<endl;
cout << "[" << setfill(' ') << setw(3) << 12345 << "]" <<endl;
cout << "[" << setfill(' ') << setw(3) << left << 12345 << "]" <<endl;

cout << "[" << 123.45 << "]" << endl;
cout << "[" << setw(11) << setprecision(5) << right << 123.45 << "]" << endl;
cout << "[" << setw(11) << setprecision(1) << 123.45 << "]" << endl;
cout << "[" << setw(11) << fixed << setprecision(1) << 123.45 << "]" << endl;
cout << "[" << setw(11) << setprecision(5) << left << 123.45 << "]" << endl;
cout << "[" << setw(11) << setfill('0') << setprecision(5) << 123.45 << "]" << endl;

return 0;
}

実行結果

T:\>lesson015\Project1.exe
[123]
[0123]
[ 123]
[123 ]
[12345]
[12345]
[12345]
[12345]
[123.45]
[ 123.45]
[ 1e+02]
[ 123.5]
[123.45000 ]
[123.4500000]