以前のリビジョンの文書です
====== C++ の備忘録 ====== ===== ストリーム ===== ==== 標準出力に出力 ==== <code c> double d1 = 123.456; double d2 = 234.567; std::cout << d1 << " , " << d2 << std::endl; </code> この出力は、\\ 123.456 , 234.567\\ となる。 <code c> std::cout << d1 << " , " << std::flush; std::cout << d2 << endl; </code> でも上と同じ出力。 === 出力の精度、桁数指定をしたい === <code c> std::cout << std::setprecision(5) << d1 << " , " << std::flush; std::cout << d2 << endl; </code> とすると、出力は\\ 123.46 , 234.57\\ となる。 * std::setprecision(n) で表示する全桁数(有効数字)を指定 * 一度指定すると、その設定がそのまま引き継がれる。 <code c> std::cout << std::fixed << std::setprecision(1) << d1 << " , " << std::flush; std::cout << d2 << endl; </code> とすると、出力は\\ 123.5 , 234.6\\ となる。 * std::fixed と std::setprecision(n) を合わせて使うことによりnは”小数点以下の桁数”の意味になる。 * これまた引き継がれる。 ===== フォーマット指定 ===== * デフォルトではフォーマット指定はfloat (%f) * 以下、std::は省略(using namespace std) ^ ^ stdio ^ iostream ^出力結果 ^ | 整数10進法表記 | printf(“%d”,123); | cout << dec << 123 << endl; | 123 | | 固定小数点表記 | printf(“%f”,1.2345); | cout << fixed << 1.2345; |1.234500| | ::: | printf(“%.2f”,1.2345); | cout << fixed << setprecision(2) << 1.2345; | 1.23 | | 指数表記 | printf(“%e”,1.2345); | cout << scientific << 1.2345; | 1.234500+e000 | | ::: | printf(“%.2E”,1.2345); | cout << scientific << setprecision(2) << uppercase << 1.2345; | 1.23+E000 | | 0埋め | printf(“%05d”,123); | cout << setfill(’0′) << setw(5) << right << 123; | 00123| | 左寄せ | printf(“%5d”,123); | cout << setw(5) << left << 123; | 123 | | 右寄せ | printf(“%5-d”,123); | cout << setw(5) << right << 123; | 123 | | 正号表示 | printf(“%+d”,123); | cout << showpos << 123; | +123 | * デフォルトに戻すには、 <code c> cout << resetiosflags(ios_base::floatfield); </code> のようにする。