std:: setw
|
定义于头文件
<iomanip>
|
||
|
/* 未指定 */
setw
(
int
n
)
;
|
||
当在表达式
out
<<
std
::
setw
(
n
)
或
in
>>
std
::
setw
(
n
)
中使用时,将流
out
或
in
的
width
参数精确设置为
n
。
某些操作会将宽度重置为零(参见
下文
),因此可能需要重复调用
std::setw
来为多个操作设置宽度。
目录 |
参数
| n | - | 宽度的新值 |
返回值
一个未指定类型的对象,使得
-
如果
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) { // 设置宽度 str.width(n); }
备注
流的宽度属性将在调用以下任一函数时重置为零(意为"未指定"):
- 输入
- 输出
-
- 接受算术类型或 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++标准。
| 缺陷报告 | 应用于 | 发布时行为 | 正确行为 |
|---|---|---|---|
| LWG 183 | C++98 |
setw
仅能用于类型为
std::ostream 或 std::istream 的流 |
可用于任意
字符流 |
参见
|
管理字段宽度
(
std::ios_base
的公开成员函数)
|
|
|
更改填充字符
(函数模板) |
|
|
设置填充字符的位置
(函数) |
|
|
控制是否使用前缀指示数值进制
(函数) |