std::setw
来自 cppreference.cn
定义于头文件 <iomanip> |
||
/* unspecified */ setw( int n ); |
||
当在表达式 out << std::setw(n) 或 in >> std::setw(n) 中使用时,将流 out 或 in 的 width
参数设置为精确的 n。
某些操作会将宽度重置为零(见下文),因此可能需要重复调用 std::setw
以设置多个操作的宽度。
内容 |
[编辑] 参数
n | - | width 的新值 |
[编辑] 返回值
一个未指定类型的对象,使得
- 如果 out 是 std::basic_ostream<CharT, Traits> 类型的对象,则表达式 out << setw(n)
- 具有类型 std::basic_ostream<CharT, Traits>&
- 具有值 out
- 行为如同调用 f(out, n)
- 如果 in 是 std::basic_istream<CharT, Traits> 类型的对象,则表达式 in >> setw(n)
- 具有类型 std::basic_istream<CharT, Traits>&
- 具有值 in
- 行为如同调用 f(in, n)
其中函数 f 定义为
void f(std::ios_base& str, int n) { // set width str.width(n); }
[编辑] 注解
如果调用以下任何函数,流的 width 属性将被重置为零(意味着“未指定”)
- 输入
- 输出
- 接受算术类型或 void 指针的 basic_ostream::operator<<() 重载(在 num_put::put() 的阶段 3)
- operator<<(basic_ostream&, char) 和 operator<<(basic_ostream&, char*)
- operator<<(basic_ostream&, basic_string&)
- std::put_money (在 money_put::put() 内部)
- std::quoted(当与输出流一起使用时)
此修饰符对输入和输出的确切影响在各个 I/O 函数之间有所不同,并在每个 operator<< 和 operator>> 重载页面中单独描述。
[编辑] 示例
运行此代码
#include <iomanip> #include <iostream> #include <sstream> int main() { std::cout << "no setw: [" << 42 << "]\n" << "setw(6): [" << std::setw(6) << 42 << "]\n" << "no setw, several elements: [" << 89 << 12 << 34 << "]\n" << "setw(6), several elements: [" << 89 << std::setw(6) << 12 << 34 << "]\n"; std::istringstream is("hello, world"); char arr[10]; is >> std::setw(6) >> arr; std::cout << "Input from \"" << is.str() << "\" with setw(6) gave \"" << arr << "\"\n"; }
输出
no setw: [42] setw(6): [ 42] no setw, several elements: [891234] setw(6), several elements: [89 1234] Input from "hello, world" with setw(6) gave "hello"
[编辑] 缺陷报告
以下行为变更缺陷报告已追溯应用于先前发布的 C++ 标准。
DR | 应用于 | 已发布行为 | 正确行为 |
---|---|---|---|
LWG 183 | C++98 | setw 只能与以下类型的流一起使用类型 std::ostream 或 std::istream |
可用于任何 字符流 |
[编辑] 参见
管理字段宽度 (std::ios_base 的公共成员函数) | |
更改填充字符 (函数模板) | |
设置填充字符的位置 (函数) | |
控制是否使用前缀来指示数字基数 (函数) |