 
 
 
 
 
 
 
  
数表のような形式でデータを出力するのに、 C では printf() で様々な書式指定をする。 もちろん C++ は C のスーパーセットなので、 printf() を使うことも可能だが、 cout ストリームと併用するのは気持ちが悪い。 以下にどうすれば良いか説明するが、あまりすっきりしない。 多くの人が C++ でも printf() を使い続けているようだが、 この辺に理由があるのかもしれない。
| 
  cout.form("N=%d, t=%g, error=%e\n", N, t, error);
 | 
| 
  printf("N=%2d, m=%3d\n", N, m);
 | 
| cout << "N="; cout.width(2); cout << N << ", m="; cout.width(3); cout << m << endl; | 
| #include <iomanip.h> ... cout << setw(2) << N << ", m=" << setw(3) << m << endl; | 
| cout.setf(ios::fixed, ios::floatfield); | 
| #include <iomanip.h> ... cout << setiosflags(fixed) | 
| cout.unsetf(ios::fixed, ios::floatfield); | 
| #include <iomanip.h> ... cout << resetiosflags(fixed) | 
| cout.setf(ios::scientific, ios::floatfield); | 
| #include <iomanip.h> ... cout << setiosflags(scientific) | 
| cout.unsetf(ios::scientific, ios::floatfield); | 
| #include <iomanip.h> ... cout << resetiosflags(scientific) | 
| cout.precision(整数式); | 
| #include <iomanip.h> .... cout << setprecision(整数式) | 
| format-sample.C | 
| #include <iostream.h>
#include <iomanip.h>
int main()
{
  int N;
  double x, y, z;
  N = 8;
  x = 1.234567890123;
  y = 123.4567890123;
  z = 123.4567890123;
  cout.form("N=%2d, x=%g, y=%22.15f, z=%e\n", N, x, y, z);
  cout << "N=" << setw(2) << N << ", x=" << x << ", y="
       << setiosflags(ios::fixed) << setw(22) << setprecision(15) << y
       << resetiosflags(ios::fixed) << setprecision(6)
       << ", z=" << setiosflags(ios::scientific) << z
       << endl;
  return 0;
}
 | 
| 実行結果 | 
| yurichan% program-cpp/format-sample N= 8, x=1.23457, y= 123.456789012300007, z=1.234568e+02 N= 8, x=1.23457, y= 123.456789012300007, z=1.234568e+02 yurichan% | 
 
 
 
 
 
 
