Deprecated: Array and string offset access syntax with curly braces is deprecated in /mnt/hep_web/hep_web/member/n-kota/dokuwiki/inc/init.php on line 542
====== 入出力ストリーム ======
----
===== 標準出力に出力 =====
double d1 = 123.456;
double d2 = 234.567;
std::cout << d1 << " , " << d2 << std::endl;
この出力は、\\
123.456 , 234.567\\
となる。
std::cout << d1 << " , " << std::flush;
std::cout << d2 << endl;
でも上と同じ出力。
==== 出力の精度、桁数指定をしたい ====
std::cout << std::setprecision(5) << d1 << " , " << std::flush;
std::cout << d2 << endl;
とすると、出力は\\
123.46 , 234.57\\
となる。
* std::setprecision(n) で表示する全桁数(有効数字)を指定
* 一度指定すると、その設定がそのまま引き継がれる。
std::cout << std::fixed << std::setprecision(1) << d1 << " , " << std::flush;
std::cout << d2 << endl;
とすると、出力は\\
123.5 , 234.6\\
となる。
* std::fixed と std::setprecision(n) を合わせて使うことによりnは”小数点以下の桁数”の意味になる。
* これまた引き継がれる。
===== フォーマット指定 =====
* デフォルトではフォーマット指定はfloat (%f)
* 以下、std::は省略(using namespace std)
* #include が必要(全部ではないかも)
^ ^ 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 |
* デフォルトに戻すには、
cout << resetiosflags(ios_base::floatfield);
のようにする。
----
===== フォーマット指定子 =====
^ フォーマット指定子 ^ 型 ^ 説明 ^
| %c | char | 文字 |
| %s | char* | 文字列 |
| %d | int,short | 10進法整数 |
| %u | unsigned int, unsigned short | 符号無し10進法整数 |
| %f | float | 浮動小数点 |
| %lf | double | 倍精度浮動小数点 |
| %e | float | 浮動小数点を指数表示 |
| %g | float | 浮動小数点を最適表示 |
| | | |
| %o | int など整数系全般 | 整数を8進法表示 |
| %x | int など整数系全般 | 整数を16進法表示 |
* %ld, %lu, %lo, %lx などもそれぞれ倍精度として用意されている
* 入力(ファイル読込)時に指定子を使うとき、%*f のように%の直後に*を入れると、そのデータは、変数に格納されずに読み飛ばされる