C++運算子(endl, setw, setprecision, setf)是什麼?


流運算子是專門設計用於與流物件上的插入(<<)和提取(>>)運算子一起使用的函式,例如:

std::cout << std::setw(10);

它們仍然是普通的函式,也可以像其他任何函式一樣使用流物件作為引數來呼叫,例如:

boolalpha (cout);

運算子用於更改流上的格式引數以及插入或提取某些特殊字元。

以下是一些最常用的C++運算子:

endl

此運算子的功能與‘\n’(換行符)相同。但它還會重新整理輸出流。

示例

線上演示

#include<iostream>
int main() {
   std::cout << "Hello" << std::endl << "World!";
}

輸出

Hello
World!

showpoint/noshowpoint

此運算子控制是否始終在浮點表示中包含小數點。

示例

線上演示

#include <iostream>
int main() {
   std::cout << "1.0 with showpoint: " << std::showpoint << 1.0 << '\n'
             << "1.0 with noshowpoint: " << std::noshowpoint << 1.0 << '\n';
}

輸出

1.0 with showpoint: 1.00000
1.0 with noshowpoint: 1

setprecision

此運算子更改浮點精度。當在表示式 out << setprecision(n) 或 in >> setprecision(n) 中使用時,將流 out 或 in 的精度引數設定為 exactly n。

示例

線上演示

#include <iostream>
#include <iomanip>
int main() {
   const long double pi = 3.141592653589793239;
   std::cout << "default precision (6): " << pi << '\n'
             << "std::setprecision(10): " << std::setprecision(10) << pi << '\n';
}

輸出

default precision (6): 3.14159
std::setprecision(10): 3.141592654

setw

此運算子更改下一個輸入/輸出欄位的寬度。當在表示式 out << setw(n) 或 in >> setw(n) 中使用時,將流 out 或 in 的寬度引數設定為 exactly n。

示例

線上演示

#include <iostream>
#include <iomanip>
int main() {
   std::cout << "no setw:" << 42 << '\n'
             << "setw(6):" << std::setw(6) << 42 << '\n'
             << "setw(6), several elements: " << 89 << std::setw(6) << 12 << 34 << '\n';
}

輸出

no setw:42
setw(6):    42
setw(6), several elements: 89    1234

更新於:2020年2月11日

4K+ 瀏覽量

啟動您的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.