操纵符是令代码能以 operator<< 或 operator>> 控制输入/输出流的帮助函数。
不以参数调用的操纵符(例如 std::cout << std::boolalpha; 或 std::cin >> std::hex; )实现为接受到流的引用为其唯一参数的函数。 basic_ostream::operator<< 和 basic_istream::operator>> 的特别重载版本接受指向这些函数的指针。这些函数(或函数模板的实例化)是标准库中仅有的可取址函数。 (C++20 起)
以参数调用的操纵符(例如 std::cout << std::setw(10); )实现为返回未指定类型对象的函数。这些操纵符定义其自身的进行请求操作的 operator<< 或 operator>> 。
定义于头文件
std::setprecision
| 定义于头文件 | ||
| /*unspecified*/ setprecision( int n ); |
用于表达式 out << setprecision(n) 或 in >> setprecision(n) 时,设置流 out 或 in 的 precision 参数准确为 n 。
| n | - | 精度的新值 |
返回未指定类型的对象,使得若 str 是 std::basic_ostream
str.precision(n);
- #include <iostream>
- #include <iomanip>
- #include <cmath>
- #include <limits>
-
- int main()
- {
- const long double pi = std::acos(-1.L);
- std::cout << "default precision (6): "
- << pi << std::endl
- << "std::setprecision(10): "
- << std::setprecision(10) << pi << std::endl
- << "max precision: "
- << std::setprecision(std::numeric_limits<long double>::digits10 + 1)
- << pi << std::endl;
-
- return 0;
- }

std::setw
| /*unspecified*/ setw( int n ); |
用于表达式 out << setw(n) 或 in >> setw(n) 时,设置流 out 或 in 的 width 参数准确为 n 。
| n | - | width 的新值 |
返回未指定类型对象,满足若 str 是 std::basic_ostream
str.width(n);
若调用任何下列函数,则流的宽度属性将被设为零(表示“不指定”):
此修改器在输入与输出上的准确效果在单独的 I/O 函数间有别,单独地描述于每个 operator<< 各 operator>> 重载的页面。
- #include <sstream>
- #include <iostream>
- #include <iomanip>
-
- int main()
- {
- std::cout << "no setw:" << 42 << std::endl
- << "setw(6):" << std::setw(6) << 42 << std::endl
- << "setw(6), several elements: " << 89
- << std::setw(6) << 12 << 34 << std::endl;
-
- std::istringstream is("hello, world");
- char arr[10];
- is >> std::setw(6) >> arr;
- std::cout << "Input from \"" << is.str()
- << "\" with setw(6) gave \""
- << arr << "\"" << std::endl;
-
- return 0;
- }
