std::iomanip

よくマニピュレータにハマッている人がいるので,メモ.

よく使うと思われる manipulator と,その動作.

setw(n) 出力幅を最低n文字にする
setprecision(n) 出力桁をn桁にする
right 出力を右に詰める
left 出力を左に詰める

setw(n)の設定だけは一度なにか値を出力するとリセットされる.

     cout << 1.23456 << endl;
     cout << setw(10) ;
     cout << 1.23456 << endl;
     cout << 1.23456 << endl;
     cout << 1.23456 << endl;

上記の実行結果は以下のようになる.

1.23456
   1.23456
1.23456
1.23456

他の設定はずっと保存される.

     cout << 1.23456 << endl;
     cout << setprecision(4);
     cout << 1.23456 << endl;
     cout << 1.23456 << endl;
     cout << 1.23456 << endl;

     cout << endl;

     cout << setw(10) << 1.23456 << endl;
     cout << right;
     cout << setw(10) << 1.23456 << endl;
     cout << setw(10) << 1.23456 << endl;
     cout << setw(10) << 1.23456 << endl;
1.23456
1.235
1.235
1.235

     1.235
     1.235
     1.235

ちなみに,setw()で幅を切り詰めると,値が四捨五入される.